Django template for loop

I have a template where I return specific variables. One variable is instance.category, which displays: "words words words", which are values ​​separated by intervals.

When I use the code below, I get letter by letter, not 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> 

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!

+8
source share
2 answers

If your separator is always " " and category is a string, you do not need a special template filter. You can simply call split without parameters:

 {% for icon in instance.category.split %} <p>{{ icon }}</p> {% endfor %} 
+13
source

You pass the string instance.category to the template, and then iterate over its characters.

Instead, pass the list to the template: instance.category.split() which will split your string words words words into the list ['words', 'words', 'words'] :

 >>> s = "words words words" >>> s.split() ['words', 'words', 'words'] 

Or you can define a custom filter that will split the string into a list:

 from django import template register = template.Library() @register.filter def split(s, splitter=" "): return s.split(splitter) 

Then use it in the template like this:

 {% for icon in instance.category|split %} <p>{{ icon }}</p> {% endfor %} 
+6
source

Source: https://habr.com/ru/post/952657/


All Articles