【问题标题】:Django cycling templatesDjango 骑行模板
【发布时间】:2011-11-25 14:02:21
【问题描述】:

我需要在Django模板中输出对象,这样每个对象都有自己的模板。模板保存在变量“模板”中 - ['path/to/template1','path/to/template2', ...]

有没有办法在对象循环中“循环”这些模板,就像这样:

{% for object in objects %}
   {% cycle templates as template %}
   {% include template %} // this code is just for example
{% endfor %}

我不能将这些模板直接包含到对象列表中,因为它是由分页器的模板标签生成的。

有什么想法吗?谢谢。

【问题讨论】:

    标签: django templates include cycle


    【解决方案1】:

    我已经编写了接收列表变量并在循环中循环的模板标签。

    from django import template
    from django.template.base import TemplateSyntaxError, Node
    
    from itertools import cycle as itertools_cycle
    
    register = template.Library()
    
    class CycleListNode(Node):
        def __init__(self, list_variable, template_variable):
            self.list_variable = list_variable
            self.template_variable = template_variable
    
        def render(self, context):
            if self not in context.render_context:
                # First time the node is rendered in template
                context.render_context[self] = itertools_cycle(context[self.list_variable])
            cycle_iter = context.render_context[self]
            value = cycle_iter.next()
            if self.template_variable:
                context[self.template_variable] = value
            return ''
    
    @register.tag
    def cycle_list(parser, token):
        args = token.split_contents()
        if len(args) != 4 or args[-2] != 'as':
            raise TemplateSyntaxError(u"Cycle_list tag should be in the format {% cycle_list list as variable %}")
        return CycleListNode(args[1], args[3])
    

    这很简单,但解决了问题。

    【讨论】:

      【解决方案2】:

      你可以创建一个模板标签来做你想要的模板,它应该接受一个路径(模板的路径)作为参数,那么你需要做的就是传递路径模板路径变量,它应该在如果您对自定义模板标签使用请求上下文,则为上下文,就像这样

      {% custom_tag path_to_template_dir %}
      

      【讨论】:

        猜你喜欢
        • 2022-06-20
        • 2020-08-23
        • 2017-09-06
        • 2017-10-19
        • 1970-01-01
        • 2022-01-12
        • 2010-10-29
        • 1970-01-01
        • 2011-04-12
        相关资源
        最近更新 更多