Skip to content

Empty string should not be truthy for block sections #2177

Description

@theodorejb

In Mustache templates it's common to use a block section to conditionally output a tag or attribute only if it has content:

{{#notes}}<p class="notes">{{notes}}</p>{{/notes}}
<button{{#id}} id="{{ id }}"{{/id}}>Click me</button>
{{#user}}
  {{name}}{{^name}}<i>Anonymous</i>{{/name}}
{{/user}}

However, Handlebars.js currently treats an empty string as truthy for block sections, which breaks templates like these.

In order to use Handlebars, all these templates would have to be modified to use the #if or #unless helper instead, which is a significant challenge for larger projects with many templates.

There was previously some discussion about this in #731. However, that was focused on the number 0 rather than the case of an empty string.

The source for the current behavior is in block-helper-missing.js. false, null, undefined, and an empty array are treated as falsy, but an empty string is not. Instead, a blank string renders the block with the context changed to the empty string, which seems unexpected and not useful.

Motivation

I'm the maintainer of PHP Handlebars, which currently matches the Handlebars.js behavior for block sections. However, the treatment of empty strings has been a roadblock for the Wikimedia design system, which has many Mustache templates that would break.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions