Home > other >  setting a dynamic data attribute on flask wtforms jinja select
setting a dynamic data attribute on flask wtforms jinja select

Time:10-29

Have a flask wtforms select field and trying to incorporate htmx ajax call, which has dashes in data attributes so I found a solution on SO like the following:

{{ form.dia(class="form-select", **{'hx-post': "/pulleys/{{pulley_id}}/hub_type", 'hx-target': "#hub-shaft-selection", 'hx-swap': "innerHTML"}) }} 

but the {{pulley_id}} doesn't get parsed by the template, I guess it's already inside another {{ }}. Is there a way to build the dynamic part as shown above so it ends up as

'hx-post'="/pulleys/1/hub_type"

when fully rendered for pulley_id=1

CodePudding user response:

If pulley_id is a variable either inside a loop or passed into render_template your should be able to format the string:

{{ form.dia(class_="form-select", **{'hx-post': "/pulleys/%s/hub_type"|format(pulley_id), 'hx-target': "#hub-shaft-selection", 'hx-swap': "innerHTML"}) }} 

Note: you also want class_ not class if you're trying to set the HTML class attribute.

  • Related