Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use Django template variable on attr or set_data #116

Open
andreccorrea opened this issue Oct 15, 2021 · 4 comments
Open

How to use Django template variable on attr or set_data #116

andreccorrea opened this issue Oct 15, 2021 · 4 comments

Comments

@andreccorrea
Copy link

Is there any way to use a template variable as param for attr or set_data tags?

Something like:

{% render_field field|set_data:"my-data:{{ template_variable }}" %}

Doing the above passes literally the string '{{ template_variable }}' to my-data attribute and not the variable value as expected.

@bblanchon
Copy link

It seems the only option is to use render_field, see #68.

@danielniccoli
Copy link

danielniccoli commented Jul 5, 2023

@bblanchon I have the same need. I am not sure if I understand your reply, because OP is already using {% render_field ... %}.

I would need a way to add a string that contains a string and the value from a variable, much like OP. Specifically, to render the aria-labelledby attribute

Both these solutions don't work:

{{ field|attr:"aria-labelledby:{{ field.label}}Help" }}
{% render_field field|aria-labelledby:"{{ field.label}}Help" %}

# Needed to link the label to the help text
{% if field.help_text %}
    <div id="{{ field.label }}Help" class="form-text">
        {{ field.help_text | safe }}
    </div>
{% endif %}

@bblanchon
Copy link

bblanchon commented Jul 6, 2023

I think what I meant to say is that @andreccorrea's only option was to do this:

{% render_field field my-data=template_variable %}

However, in your case @danielniccoli, you must append "help" to the string before passing it to {% render_field %}.
As far as I know, you cannot do this in one shot, so you need to create an additional context variable using {% with %}, like so:

{% with help_id=form.name.id_for_label|add:'_help' %}
{% render_field field aria-labelledby=help_id %}
<div id="{{ help_id }}" class="form-text">{{ field.help_text }}</div>
{% endwith %}

@danielniccoli
Copy link

danielniccoli commented Jul 6, 2023

{% with help_id=form.name.id_for_label|add:'_help' %}
                                       ^^^                                              

That solved my problem! I wasn't aware I could use |add that way. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants