2
@laffuste has a good point that you need to use the as
command to store the array into a template variable before you iterate through it. However, there’s a slightly neater way to write the tag — this is, in fact, precisely what Assignment Tags were made for:
from django import template
register = template.Library()
@register.assignment_tag(takes_context=True)
def create_array(context):
return [1,2,3,4]
That’s it — the assignment tag does the nasty work of parsing and return a template-variable-friendly output. Everything in laffuste’s answer for the template is exactly what you’d need, but just so you can have it all in one place, here it is reproduced again so it’s all in one place:
{{ load my_custom_tags }}
{% create_array as my_array %}
{% for item in my_array %}
{{ item }}
{% endfor %}
0
To get an index of each object in the forloop
, use a forloop.counter
like so:
{% load create_array %}
{% for i in create_array %}
{{ forloop.counter }}
{% forend %}
If you want to do something when you hit a certain count in the forloop, then use the following code:
{% for i in create_array %}
{% if forloop.counter == 1 %}
Do something with {{ i }}.
{% endif %}
{% endfor %}
Here is the Django Documentation for the forloop counter:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
- [Answered ]-Adding an ImageField to already existing model in django
- [Answered ]-Merge unknown amount of querysets in django
0
I’m afraid there’s no simpler way than…
from django import template
from django.template.base import TemplateSyntaxError
register = template.Library()
@register.tag(name='create_array')
def create_array(parser, token):
class ArrayCreator(template.Node):
def __init__(self, var_name):
self.var_name = var_name # output variable
def render(self, context):
context[self.var_name] = [1, 2, 3, 4] # access to context
return ''
args = token.contents.split() # "create_array", "as", VAR_NAME
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError("'create_array' requires 'as variable' (got %r)" % args)
return ArrayCreator(args[2])
Usage in Template:
{{ load my_custom_tags }}
{% create_array as my_array %}
{% for item in my_array %}
{{ item }}
{% endfor %}
But maybe someone will come with something lighter and nicer?