【问题标题】:join template block-tag in django在 django 中加入模板块标签
【发布时间】:2009-11-03 18:08:38
【问题描述】:

有没有人写过一个块模板标签,用一些分隔符连接任意 html sn-ps,其中省略了空项?

可用于呈现类似菜单的列表,其中显示的项目是在运行时确定的,而要连接的项目需要精细的标记。

谢谢。

例如:

{% joinitems using ' | ' %}

  {% if show_a %}
  <p>Some HTML here</p>
  {% endif %}    

{% separator %}

  {% if show_b %}
  <p>And some here</p>
  {% endif %}

{% endjoinitems %}

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    整整一个小时都没有答案……不可接受。所以我自己把这个放在一起。

    class ItemSeparatorNode(template.Node):
        def __init__(self,separator):
            sep = separator.strip()
            if sep[0] == sep[-1] and sep[0] in ('\'','"'):
                sep = sep[1:-1]
            else:
                raise template.TemplateSyntaxError('separator in joinitems tag must be quoted')
            self.content = sep
        def render(self,context):
            return self.content
    
    class JoinItemListNode(template.Node):
        def __init__(self,separator=ItemSeparatorNode("''"), items=()):
            self.separator = separator
            self.items = items
        def render(self,context):
            out = []
            empty_re = re.compile(r'^\s*$')
            for item in self.items:
                bit = item.render(context)
                if not empty_re.search(bit):
                    out.append(bit)
            return self.separator.render(context).join(out)
    
    @register.tag(name="joinitems")
    def joinitems(parser,token):
        try:
            tagname,junk,sep_token = token.split_contents()
        except ValueError:
            raise template.TemplateSyntaxError("joinitems tag requires 'using \"separator html\"' parameters")
        if junk == 'using':
            sep_node = ItemSeparatorNode(sep_token)
        else:
            raise template.TemplateSyntaxError("joinitems tag requires 'using \"separator html\"' parameters")
        nodelist = []
        while True:
            nodelist.append(parser.parse(('separator','endjoinitems')))
            next = parser.next_token()
            if next.contents == 'endjoinitems':
                break
    
        return JoinItemListNode(separator=sep_node,items=nodelist)
    

    【讨论】:

    • 嘿嘿-我一直都在这样做...问这个问题,然后再猜测自己,当我不耐烦的时候自己去寻找答案。
    猜你喜欢
    • 2011-02-09
    • 2018-10-21
    • 1970-01-01
    • 2010-09-20
    • 2014-03-20
    • 2011-04-06
    • 1970-01-01
    • 2013-06-05
    • 2016-11-21
    相关资源
    最近更新 更多