2011-11-25 115 views
0

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

有没有办法在对象循环中“循环”这些模板? ,不知何故:

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

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

任何想法?谢谢。

回答

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

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

-1

您可以创建一个模板标签,它可以根据您的需要使用模板,它应该将路径(模板路径)作为参数,然后您需要做的就是传递应该是路径模板路径变量在上下文中,如果您使用请求上下文来您的自定义模板标签,像这样

{% custom_tag path_to_template_dir %}