我试图用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)
我也遇到过同样的问题,在看了你的问题后,我设法做到了。希望这能帮助其他人。在
我正在我的项目中使用classy-tags,我强烈推荐它。如果您只打算使用一次,那么代码可能很简单。因为我的目的是要有不同种类的面板,所以我使它有点通用。在
模板如下:
^{2}$下面是如何使用它:
这可以通过使用Jinja2 Macros轻松完成。希望django1.8将带来本地Jinja2支持。在
我相信你要找的答案已经写在文件里了, https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#passing-template-variables-to-the-tag
转到简单标记部分,它详细介绍了如何按您想要的方式传递vairable
然后在模板中,可以将任意数量的参数(用空格分隔)传递给模板标记。与Python一样,关键字参数的值是使用等号(“=”)设置的,并且必须在位置参数之后提供。例如:
^{2}$相关问题 更多 >
编程相关推荐