-1

我有一个模型树,并使用模型使用自定义模板标签自行递归渲染。

每个 Widget 模型都有自己的模板和上下文数据,并且可以自己渲染。小部件可能有子小部件模型,子小部件将首先被渲染,父小部件可以组装它们。

并且模板使用自定义标签。

型号代码

class Widget(models.Model):
slug = models.SlugField(max_length=255, unique=True)
title = models.CharField(max_length=50, blank=True)
sub_title = models.CharField(max_length=50, blank=True)
parent = models.ForeignKey('self', null=True, blank=True,
        related_name='widget', verbose_name=u'')
position = models.PositiveSmallIntegerField(default=1);
links = models.ManyToManyField(Link)
template = models.FilePathField(
           path='templates/widgets/',
           match='.*.html$', choices=WIDGETS_TEMPLATE, blank=True)
content = models.TextField(default="{}")

objects = WidgetManager()

def __unicode__(self):
    return self.title

def get_template(self):
    return path.join(settings.PROJECT_PATH, self.template)

def get_content(self):
    return self.content

def get_template_slug(self):
    return self.template.split('/')[-1][:-5]

def get_content_json(self):
    # return self.encodeContent()
    return json.loads(self.content)

标记代码

class WidgetNode(template.Node):

def __init__(self, position):
    self.template = 'widgets/index-cools-subs.html'
    # print template.Variable(self.positon)
    self.position = template.Variable(self.position)

def render(self, context):
    widgets = context['widgets']
    attrs = {}
    for widget in widgets:
        if widget.position == self.position:
            children = Widget.objects.filter(parent=widget)
            if children:
                attrs['widgets'] = [child for child in children]
            else:
                attrs = widget.get_content_json()
            self.template = widget.get_template()
    return render_to_string(self.template, attrs)

def widget(parser, token):
try:
    tag_name, position = token.split_contents()
except ValueError:
    msg = 'widget %s value error.' % token
    raise template.TemplateSyntaxError(msg)
return WidgetNode(position)

模板代码

<div class="section" name="subs" fd="index">
{% for widget in widgets %}
  {% widget widget.position %}
{% endfor %}
</div>

我有两个问题:

  • template.Variable 为空,可能是逻辑错误或其他错误。
  • 自定义标签在 for 循环中没有意义,它不会在循环中调用。

非常感谢任何建议。

谢谢。

4

1 回答 1

1

Django 仅__init__在“构建”模板时执行,仅render()在调用渲染时执行。因此,您需要使用模板变量进行这种摆弄,当self.position = template.Variable(self.position)您执行诸如仅告诉 Djangoself.position模板上下文中定义的变量而不是其值的操作时;要获得渲染时需要解决的值:

def render(self, context):
    position = self.position.resolve(context)
    # do something with position...
于 2013-06-04T10:50:57.140 回答