2013-08-28 3 views
6

특정 변수를 다시 가져 오는 템플릿이 있습니다. 하나의 변수는 instance.category를 출력합니다. "words words words"는 간격으로 분리 된 값입니다.루프 용 Django 템플릿

아래 코드를 사용하면 문자가 아닌 문자로 문자를 얻을 수 있습니다.

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

출력

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

내가 필요 : 어떤 도움에 감사드립니다

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

장고 플러그인 코드

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) 
!

+0

당신이 우리에게보기 카테고리를 살펴 가질 수를 표시 할 수 있습니다 : 당신은 단순히 매개 변수없이 split를 호출 할 수 있을까? –

+0

FilerImage 플러그인을 재정의하여 포트폴리오 항목에 대한 추가 필드를 추가합니다. 이게 도움이 되나요? –

답변

12

구분 기호가 항상 " "이고 category 인 경우 실제로 사용자 지정 템플릿 필터가 필요하지 않습니다.

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

맞습니다! 고마워. –

+0

+1 멋지고 간단합니다! – alecxe

6

instance.category 문자열을 템플릿에 전달한 다음 해당 문자를 반복합니다. 목록 ['words', 'words', 'words']words words words 문자열을 분할합니다 instance.category.split() : 대신

이 템플릿에 대한 목록을 통과

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

또는, 당신은 목록에 문자열을 분할하는 custom filter를 정의 할 수 있습니다 그런 다음

from django import template 
register = template.Library() 

@register.filter 
def split(s, splitter=" "): 
    return s.split(splitter) 

는 템플릿에이 방법을 사용 :

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

사용자 정의 필터를 사용하고 있는데이 오류가 발생합니다. 'for'문은 'for x in y'형식을 사용해야합니다. instance.category | split의 아이콘 : ""어떤 아이디어입니까? –

+0

@NielsenRamon 확실하게 업데이트 된 답변을 참조하십시오. – alecxe

+0

흠 아직도 동일한 오류 :/ –

관련 문제