Skip to main content

How to Conditionally Render a Field in an HTML Template

Updated this week

Overview

When working with dynamic HTML templates (for example, in PDF.co), you may want to display certain fields only when they exist or have a value.

Handlebars provides a simple built-in helper — #if — that allows you to conditionally render parts of your HTML based on the presence or value of a field.


Example Use Case

Let’s say your template includes a “location” field that should appear only when it’s provided in the input data.
You can use the #if helper like this:

{{#if location}}
<div class="detail-row">
<span class="detail-label">Celebrado en:</span>
<span class="detail-value">{{location}}</span>
</div
{{/if}}

How It Works

  • The block inside {{#if location}} ... {{/if}} is rendered only if the location field exists and has a value.

  • If location is missing, null, or an empty string, nothing inside the block will be displayed in the final output.


Example Behavior

When the input includes a location

Input JSON:

{   "location": "Madrid, Spain" }

Rendered Output:

Celebrado en: Madrid, Spain

When the input does not include a location

Input JSON:

{}

Rendered Output:

(no HTML is rendered for the location field)

Additional Resources

You can use Handlebars helpers like #if, #unless, and #each to control your HTML logic:
🔗 Built-in Handlebars Helpers Guide

To define your own helper functions (for example, to calculate totals or format data):
🔗 Handlebars Custom Helpers Documentation

You can also test your helpers and templates directly in the Handlebars online playground:
🔗 Handlebars Playground – SafeString Example


Summary

The #if helper is the easiest way to conditionally render fields in your HTML templates.
Use it whenever you want certain elements (like location, address, or notes) to appear only when data is present, keeping your final output clean and professional.

Did this answer your question?