如何将参数传递给Django的自定义模板(块)标记

2024-10-01 09:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用django制作可重用的接口组件。我可以用定制的模板标签实现一些功能:

{% panel %}
    Some panel content
{% endpanel %}

它工作得很好,但我不能通过小组标题作为一个论点。我真正想要的是:

^{pr2}$

我在文件里找不到答案。有办法实现吗?如果没有,有没有其他的策略我可以使用?在

edit: Keep in mind that the panel content is suposed to accept more markup inside, like other tags and blocks. That's why a simple template tag was not enough for me.


细节

在面板.html在

<div class="panel panel-default">
    <div class="panel-heading">{{ title|default:"Panel Title" }}</div>
    <div class="panel-body">
        {{ body }}
    </div>
</div>

模板标签/主题.py在

from django import template


register = template.Library()


@register.tag
def panel(parser, token):
    nodelist = parser.parse(('endpanel',))
    parser.delete_first_token()
    return PanelNode(nodelist)


class PanelNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        output = self.nodelist.render(context)
        t = template.loader.get_template('theme/blocks/panel.html')
        c = template.Context({'body': output})
        return t.render(c)

Tags: djangoselfdiv模板parserdefbodytemplate
2条回答

我也遇到过同样的问题,在看了你的问题后,我设法做到了。希望这能帮助其他人。在

我正在我的项目中使用classy-tags,我强烈推荐它。如果您只打算使用一次,那么代码可能很简单。因为我的目的是要有不同种类的面板,所以我使它有点通用。在

# templatetags/modals.py
from classytags.core import Tag, Options
from classytags.arguments import Argument, MultiKeywordArgument
from django import template

register = template.Library()


class BasePanel(Tag):

    def render_tag(self, context, **kwargs):

        nodelist = kwargs.pop('nodelist')
        body = nodelist.render(context)

        panel_context = self.get_panel_context(kwargs)
        panel_context['body'] = body

        t = template.loader.get_template(self.template)
        c = template.Context(kwargs)

        return t.render(c)

    def get_panel_context(self, arguments):
        """
            Override this method if you're using fancy arguments,
            e.g: MultiKeywordArgument
        """
        return arguments


class ExamplePanel(BasePanel):
    name = 'panel'
    template = 'main/modals/panel.html'
    options = Options(
        Argument('title'),
        MultiKeywordArgument('kw', required=False),
        blocks=[('endpanel', 'nodelist')],
    )

    def get_panel_context(self, arguments):
        kw = arguments.pop('kw')
        arguments['state'] = kw.get('state', 'default')
        return arguments

register.tag(ExamplePanel)

模板如下:

^{2}$

下面是如何使用它:

{% panel "First Title" state="primary" %}

<p>Hello World!</p>

{% endpanel %}

{% panel "Another Title" %}

<p>Hello World!</p>

{% endpanel %}

这可以通过使用Jinja2 Macros轻松完成。希望django1.8将带来本地Jinja2支持。在

我相信你要找的答案已经写在文件里了, https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#passing-template-variables-to-the-tag

转到简单标记部分,它详细介绍了如何按您想要的方式传递vairable

@register.simple_tag
def my_tag(a, b, *args, **kwargs):
    warning = kwargs['warning']
    profile = kwargs['profile']
    ...
    return ...

然后在模板中,可以将任意数量的参数(用空格分隔)传递给模板标记。与Python一样,关键字参数的值是使用等号(“=”)设置的,并且必须在位置参数之后提供。例如:

^{2}$

相关问题 更多 >