Reputation: 6544
So, in template.html I use:
{% if dict %}
{{ s={} }}
{% endif %}
The error is - Could not parse the remainder: '={}' from 's={}'. How to fix it?
Upvotes: 2
Views: 9717
Reputation: 2753
It is still first in google search and it doesn't have good solution. (in my opinion)
my solution:
custom template tag
from django import template
import ast
register = template.Library()
@register.simple_tag
def create_dict(str_dict):
return ast.literal_eval(str_dict)
and then in template
{% load yout_tag_file %}
{% create_dict "{ 'my_val_1': ['test', 'test', 'test'],'my_val_2': 2, }" as config %}
{% for key, value in config.items %}
{{key}} - {{value}}
{% endfor %}
Upvotes: 5
Reputation: 468
If you use Jinja2 with Django, you can do this. Jinja2 has more functionalities and performance than Django Template Library. In Jinja2 you can set dict like this:
{% set my_dict = { 'my_val_1': 1,'my_val_2': 2, } %}
Also, you can update the dict variable inside the loops.this skips the scope issue's.
Upvotes: 0
Reputation: 4318
Django templates shouldn't really be used for making dictionaries, they should be made in your views and only basic processing should be done in the templates.
It's this way on purpose to strictly adhere to the MVC design pattern.
See from here: https://docs.djangoproject.com/en/dev/topics/templates/
Philosophy
If you have a background in programming, or if you’re used to languages like PHP which mix programming code directly into HTML, you’ll want to bear in mind that the Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic.
The Django template system provides tags which function similarly to some programming constructs – an if tag for boolean tests, a for tag for looping, etc. – but these are not simply executed as the corresponding Python code, and the template system will not execute arbitrary Python expressions. Only the tags, filters and syntax listed below are supported by default (although you can add your own extensions to the template language as needed).
By the looks of things you want to create a dict
based on some condition. You should probably rearrange your logic and create the dict
in the view -- you also get to leverage all the power of python this way.
There's probably be a ton of workarounds for your situation if you describe it in more detail.
Upvotes: 3
Reputation: 26778
You can't directly put python code in the template. But you can set variables to certain values on if conditions. You can do that using the with tag
{% with alpha=1 beta=2 %}
...
{% endwith %}
Upvotes: 0
Reputation: 5864
You can not do that in template. This is not what templates are for. You should do this logic on a view or custom template tag instead.
Upvotes: 0