Skip to content

New operator proposal: Conditional block that wont loop when given a list #14

@nickretallack

Description

@nickretallack

This is a common idiom you'll see in the form-handling code in every framework out there:

{% if form.errors %}
<div class="errors">
  <h1>Your form has errors in it!</h1>
  <ul>{% for error in form.errors %}
    <li>{{error}}</li>
  {% endfor %}</ul>
</div>
{% endif %}

Now, how do you implement this in mustache? You can't just make "if form.errors" a section or it would trigger a loop. You would have to pass in an additional flag to indicate that the list is empty. In fact, you'd have to do this any time you wanted to omit rendering the scaffolding around an empty list. And that's no fun.

This happens because mustache uses the same syntax for loops and conditionals. It'd be really nice to have two different operators here, so we could consider a non-empty list to be a normal truthy value without looping on it.

I propose we implement a ? operator that acts just like # except that it does not loop when given a list. This is your conditional operator that only cares about truthiness.

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