for循环变量在templatetag中使用?

发布于 2024-08-28 18:38:54 字数 1401 浏览 9 评论 0原文

尝试解决模板标签的问题。

我有两个模板标签:

@register.inclusion_tag('directory/_alphabet.html')
def alphabet_list(names):
    """ Return a list of letters that last names start with. """
    return { 'letters': [name.last_name[0] for name in names] }

class NameNode(template.Node):
    def __init__(self, letter, var_name):
        self.letter = letter
        self.var_name = var_name

    def render(self, context):
        context[self.var_name] = Person.objects.get_active().filter(
            last_name__istartswith=self.letter)
        return ''

@register.tag
def get_names(parser, token):
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % \
                token.contents.split()[0]
    m = re.search(r'for (.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % \
              tag_name
    letter, var_name = m.groups()
    return NameNode(letter, var_name)

我想像这样使用它们:

{% for letter in letters %}
<h2>{{ letter }}</h2>
{% get_names for letter as names %}
<ul>
    {% for name in names %}
    <li>{{ name }}</li>
    {% endfor %}
</ul>
{% endfor %}

但是“字母”作为单词“字母”发送,而不是作为变量应包含的任何字母发送。有没有办法解决这个问题或我缺少的东西(或者更好的是,已经有一个包可以做到这一点)?

Trying to solve a problem with templatetags.

I have two templatetags:

@register.inclusion_tag('directory/_alphabet.html')
def alphabet_list(names):
    """ Return a list of letters that last names start with. """
    return { 'letters': [name.last_name[0] for name in names] }

class NameNode(template.Node):
    def __init__(self, letter, var_name):
        self.letter = letter
        self.var_name = var_name

    def render(self, context):
        context[self.var_name] = Person.objects.get_active().filter(
            last_name__istartswith=self.letter)
        return ''

@register.tag
def get_names(parser, token):
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % \
                token.contents.split()[0]
    m = re.search(r'for (.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % \
              tag_name
    letter, var_name = m.groups()
    return NameNode(letter, var_name)

And I want to use them like so:

{% for letter in letters %}
<h2>{{ letter }}</h2>
{% get_names for letter as names %}
<ul>
    {% for name in names %}
    <li>{{ name }}</li>
    {% endfor %}
</ul>
{% endfor %}

But 'letter' gets sent as the word 'letter' and not as whatever letter the variable should contain. Is there a way around this or something I'm missing (or, better yet, a package that already does this)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自此以后,行同陌路 2024-09-04 18:38:54

您会得到字符串“letter”,因为这是模板解析器从模板源中读取的内容。如果您想访问此变量的值,则必须在 NameNode.__init__ 中将其标记为模板变量,并使用 render< 中的上下文解析它。 /代码>。

如下:

class NameNode(template.Node):
    def __init__(self, letter, var_name):
        self.letter = template.Variable(letter)
        self.var_name = var_name

    def render(self, context):
        try:
            context[self.var_name] = Person.objects.get_active().filter(
                last_name__istartswith=self.letter.resolve(context))
        except template.VariableDoesNotExist:
            pass
        return ''

文档中对此进行了解释 此处

You get the string "letter" because this is what the template parser read from your template source. If you want to access the value of this variable, you have to mark it as a template variable in NameNode.__init__ and resolve it using the context in render.

As follow:

class NameNode(template.Node):
    def __init__(self, letter, var_name):
        self.letter = template.Variable(letter)
        self.var_name = var_name

    def render(self, context):
        try:
            context[self.var_name] = Person.objects.get_active().filter(
                last_name__istartswith=self.letter.resolve(context))
        except template.VariableDoesNotExist:
            pass
        return ''

It's explained in the docs here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文