如果我正确理解了您的问题(这里已经很晚了),您需要一种基于插件实例覆盖插件模板的方法,因为破解 django 模板不是可行的方法(我同意)。
Django CMS 确实允许您基于实例覆盖插件模板。
如图http://docs.django-cms.org/en/develop/how_to/custom_plugins.html?highlight=get_render_template#the-simplest-plugin
在您的 CMSPluginBase 子类中添加以下内容:
def get_render_template(self, context, instance, placeholder):
# criteria goes here
return 'sometemplate.html'
至于如何知道何时(条件)渲染哪个模板,您可以做一些事情。
使用页面的反向 id:
page = instance.page
templates = {
'homepage': 'plugin_home.html',
'about': 'plugin_about.html',
'contact': 'plugin_contact.html',
}
return templates[plugin.page.reverse_id]
这种方法有一些缺点:
- 依赖于绑定到页面的插件。 (插件可以存在于页面之外)
- 只能用于设置了反向 ID 和反向 ID 的页面
每页都是唯一的,这意味着您必须列出反向 id
对于您要为其更改模板的每个页面。
使用 page 扩展来设置每个页面的类别:
结帐http://docs.django-cms.org/en/develop/how_to/extending_page_title.html
使用这种方法,您可以为多个页面设置某种类别,这样您就可以一次定位多个页面,如下所示:
page = instance.page
extension = get_page_extension(page) # Check out docs for this
templates = {
'category_1': 'plugin_category_1.html',
'category_2': 'plugin_category_2.html',
'category_3': 'plugin_category_3.html',
}
return templates[extension.category.name]
优点:
缺点:
使用模板上下文变量:
在您的模板中,根据您呈现插件的方式,您可以
像这样提供一个上下文变量:
{% with category='category_1' %}
{% placeholder 'content' %}
{% endwith %}
或
{% with category='category_1' %}
{% render_plugin yourplugin %}
{% endwith %}
然后在您的 get_render_template 方法中,您可以访问此上下文变量并执行以下操作:
# Use .get() to provide fallback
category = context['category']
templates = {
'category_1': 'plugin_category_1.html',
'category_2': 'plugin_category_2.html',
'category_3': 'plugin_category_3.html',
}
return templates[category]
优点:
缺点:
- 我唯一能想到的就是这些随机的
{% with %} in
模板。
我完全错过了新博客部分,所以为了覆盖新闻博客插件或任何插件,只需将要覆盖的插件类子类化并取消注册原始插件,然后注册你的,确保你的插件具有相同的类名。
也许您可以将上面的整个模板逻辑制作成一个 mixin,以便在整个项目中使用。