I’m looking to set a default behavior in a template to be included.
I have a problem with Django template system not allowing to set variables in template (I’ve read about the Django Philosophy, and I understand it).
Here is my example problem:
-
I want to include a template to render a newsfeed:
template.html: ... {% include "_newsfeed.html" with slicing=":20" %} ...I would like to not be forced to enter the
slicingargument, and set a default behavior, let’s say":20" -
In my
_newsfeed.html, I would like to do (pseudo-code, it doesn’t work):_newsfeed.html: ... {% if not slicing %}{% with slicing=":20" %}{% endif %} {% for content in newsfeed_content|slice:slicing %} {# Display content #} {% endfor %} {% if not slicing %}{% endwith %}{% endif %}
Instead, I end up doing this below, that doesn’t follow the DRY rule (and doesn’t satisfy me!):
_newsfeed.html:
...
{% if not slicing %}{% with slicing=":20" %}
{% for content in newsfeed_content|slice:slicing %}
{# Display content #}
{% endfor %}
{% endwith %}{% else %}
{% for content in newsfeed_content|slice:slicing %}
{# Display content #}
{% endfor %}
{% endif %}
How should I do ?
If you want to do this via your template not your views file, you could create your own filter based on slice e.g.