mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 635 forks source link

Shorthand conditional with quote and variable issue #1408

Open aboutjquery opened 2 years ago

aboutjquery commented 2 years ago
{% macro example(maxWidth) %}
  <div {{ 'style="max-width: ' + maxWidth + '"' | safe if maxWidth }}></div>
{% endmacro %}

{{ example(maxWidth = '10rem') }}

The macro quote is escaped in the html source code, which is not what I want. Actually safe doesn't work here, it should be because it's in the wrong place, but I don't know where to put it. <div style=&quot;max-width: 10rem&quot;</div>

This is the result I want, is there a way to keep the inline structure of the shorthand to solve it? <div style="max-width: 10rem"></div>

For the time being, I can only give up the inline structure and use set to add a variable to solve.

{% set style = 'style="max-wdith: ' + maxWidth + '"' if maxWidth %}
<div {{ style | safe }}></div>

Thanks for help.