Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 form render does not allow attribute which contains "-"

I am trying to customize the form template base on this tutorial. As I understand, render() just add some attributes to the tag. For example, I add placeholder = "abc" and it works well.

{% call inserttourbus(id = "formAddNewRow" )  %}

     <div class="fieldWrapper">
         {% if inserttourbus['bustype'].label() %}Bus Type{% endif %}
         {{ inserttourbus['bustype'].render(placeholder="abc")|safe }}
         {% if inserttourbus['bustype'].errors() %}Not filled yet!{% endif %}      
     </div>
{% endcall %}

Here is my problem: - I use bootstrap typeahead for my template so I need to add the following attribute to the inserttourbus textbox

data-provide="typeahead" data-items="4" data-source='["Alabama","Alaska"]'

So it will become

{{ inserttourbus['bustype'].render(placeholder="abc", data-provide="typeahead", data-items="4", data-source='["Alabama","Alaska"]')|safe }}

But the jinja2 engine seems does not accept data-provide, data-items, so on because it contain "-" character. If I changed data-provide to dataprovide, the jinja2 engine can render the code well.

However, in bootstrap typeahead javascript, all variables are defined as data-provide, data-items. If I change them to dataprovide, dataitems, the javascipt stop working.

Please give me a solution: - How to make jinja2 accept attribute which has "-" - Other solutions, advices

like image 926
John Avatar asked Feb 24 '26 01:02

John


2 Answers

Check out this snippet for doing this in Flask. I imagine it would work the same way for Django; pass HTML attributes with invalid Jinja2 (Python) syntax inside an ad-hoc dictionary:

{{ inserttourbus['bustype'].render(placeholder="abc", 
       **{'data-provide':'typeahead',
          'data-items':'4',
          'data-source':'["Alabama","Alaska"]'}) }}
like image 189
Josh Klein Avatar answered Feb 26 '26 01:02

Josh Klein


A Hyphen is used as the subtraction operator in Python. So do not use it in names. You can use it ofcourse in strings.

like image 43
voscausa Avatar answered Feb 26 '26 02:02

voscausa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!