在Django中编写模板标签 [英] Writing a Template Tag in Django

查看:126
本文介绍了在Django中编写模板标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自定义用Django编写的CMS。内容编辑器不够灵活,所以我想提出一个更好的解决方案。

I'm trying to customise a CMS written in Django. The content editors aren't flexible enough so I'm trying to come up with a better solution.

没有过度解释,我希望它成为一个像 django-better-chunks Django的flatblocks 。您可以从模板中完全设置可编辑区域。我想将这些可编辑区域绑定到混合的字符串和对象实例。一个例子是根据一个产品拥有多个可编辑区域:

Without over-explaining it, I'd like it to be a bit like django-better-chunks or django-flatblocks. You set up an editable region entirely from within the template. I want to bind these editable regions to a mix of strings and object instances. One example would be having multiple editable regions based on one product:

{% block product_instance "title" %}
{% block product_instance "product description" %}

所以如果您有另一个产品的视图为 product_instance 这两个将显示不同的数据。我还会看到只有通过字符串部分的站点范围的块才能使用。基本上,我想要能够传递1无穷大的标识符。

So if you have a view with another product as product_instance those two blocks would show different data. I would also see there being use for site-wide blocks that only pass through the string part. Essentially, I would like to be able to pass 1-infinity identifiers.

但是我在这两个方面真的很挣扎:

But I'm really struggling on two fronts here:


  1. 如何定义混合标识符与实际内容实例之间的关系?我有一个感觉contenttypes可能在这里可能,但我真的不知道从哪里开始看!

  1. How do I define the relationship between the mixed identifier and the actual content "block" instance? I have a feeling contenttypes might feature here but I've really no idea where to start looking!

我如何写一个模板标签来阅读上面语法并将其转换为呈现的对象?

And how do I write a template tag to read the above syntax and convert that into an object for rendering?


推荐答案

可以创建一个包含标签并使用它:

for this you can create an inclusion tag and use it like:

{% load my_tags %}
{% product bicycle <extra vars ...> %}

要定义标签,请添加到您的app / templatetags / mytags.py:


To define the tag, add to your app/templatetags/mytags.py:

@register.inclusion_tag('results.html')
def product(item, *extra):
    #maybe repackage extra variables
    #and add them to the returned dictionary
    item_form = ItemForm(item) #form.ModelForm instance
    return {'item': item, 'item_form':item_form, ...}

然后,您需要一个返回项目的HTML的模板:

Then you'll need a template that returns html for the item:

<h1>{{item.title}}</h1>
{{item_form}}
... add some conditional statements depending on extra vars

这篇关于在Django中编写模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆