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 634 forks source link

Bug: Specific if condition is not working inside an input html tag #1460

Closed BernaLang closed 4 months ago

BernaLang commented 4 months ago

I'm trying to render a dynamic input using nunjucks latest version (3.2.4). I have this template:

<div>
  <input
    type="text"
    value="{{validation.maxlength}}"
    {% if validation.required %} required {% endif %}
    {% if validation.maxlength %} maxlength="{{validation.maxlength}}" {% endif %}
  />
  <div class="message">
    {% if validation.maxlength %} Works! {% endif %}
  </div>
</div>

And when I render: nunjucks.render(template, { validation: { required: true, maxlength: 5 } })

I get a really weird behaviour. The input renders with the properties value=5 and required but it doesn't render with the maxlength property. On top of that, the message "Works!" also shows correctly. I've also tried changing the if a bit (like returning a simple disabled property) but it still won't work.

Could this be a possible issue on nunjucks or am I missing something here?

devoidfury commented 4 months ago

I'm not seeing this behavior; can you provide a reproducible sample? Nunjucks doesn't read html (it's just treated as string output) so there's nothing here that should cause a special case.

My gut feeling is, you're running stale cached templates, or there's something else going on there.

[devoidfury@mini devcli]$ node
Welcome to Node.js v21.2.0.
Type ".help" for more information.
> const nunjucks = require('nunjucks')
undefined
> const template = `<div>
...   <div>
...     <input
...       type="text"
...       value="{{validation.maxlength}}"
...       {% if validation.required %} required {% endif %}
...       {% if validation.maxlength %} maxlength="{{validation.maxlength}}" {% endif %}
...     />
...     <div class="message">
...       {% if validation.maxlength %} Works! {% endif %}
...     </div>
...   </div>
... </div>`
undefined
> console.log(nunjucks.renderString(template, { validation: { required: true, maxlength: 5 } }))
<div>
  <div>
    <input
      type="text"
      value="5"
       required 
       maxlength="5" 
    />
    <div class="message">
       Works! 
    </div>
  </div>
</div>
BernaLang commented 4 months ago

After some more extensive debugging we figured it out. Turns out it was our gulp configuration that was altering that specific condition when compiling the templates. Will close the issue, thanks for the response!