Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template for loop

I have a template where I get certain variables back. One variable is instance.category which outputs: "words words words" which are values split by spaced.

When I use the code below I get letter by letter back and not the words.

{% for icon in instance.category  %}
  <p>{{ icon }}</p>
{% endfor %}

Output

<p>w</p>
<p>o</p>
<p>r</p>
<p>d</p>
<p>w</p>
....

I need:

<p>word</p>
<p>word</p>
<p>word</p>

The Django plugin code

from cmsplugin_filer_image.cms_plugins import FilerImagePlugin
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _
from models import Item

class PortfolioItemPlugin(FilerImagePlugin):
    model = Item
    name = "Portfolio item"
    render_template = "portfolio/item.html"
    fieldsets = (
        (None, {
            'fields': ('title', 'category',)
        }),
        (None, {
            'fields': (('image', 'image_url',), 'alt_text',)
        }),
        (_('Image resizing options'), {
            'fields': (
                'use_original_image',
                ('width', 'height', 'crop', 'upscale'),
                'use_autoscale',
            )
        }),
        (_('More'), {
            'classes': ('collapse',),
            'fields': (('free_link', 'page_link', 'file_link', 'original_link', 'target_blank'),)
        }),
    )

plugin_pool.register_plugin(PortfolioItemPlugin)

Any help is appreciated!

like image 636
Nielsen Ramon Avatar asked Aug 28 '13 12:08

Nielsen Ramon


People also ask

Which Django template syntax allows to use the for loop?

To create and use for loop in Django, we generally use the “for” template tag. This tag helps to loop over the items in the given array, and the item is made available in the context variable.

What is Forloop counter in Django?

But Django brings in the box an automatically creates a variable called forloop. counter that holds the current iteration index. {% for variable in variables %} {{ forloop.counter }} : {{ variable.variable_name }} {% endfor %} The forloop.


1 Answers

If your separator is always " " and category is a string, you don't actually need a custom template filter. You could simply call split with no parameters:

{% for icon in instance.category.split %}
  <p>{{ icon }}</p>
{% endfor %}
like image 65
augustomen Avatar answered Sep 25 '22 21:09

augustomen