django-cms "summary view"从多个页面聚合内容

标签 django django-templates django-cms

Django==1.5.1
django-cms==2.4.1

我想从 django-cms 中选定页面的所有子页面创建一个摘要 View ,拉出标题,截断内容等,并为每个列出的 child 提供更多...链接。我已经设法获得标题和路径,但我很难从占位符中获取内容。

我有一个这样的模板标签:

from cms.models import Page
from cms.utils.page_resolver import get_page_from_path

from django import template


register = template.Library()


@register.inclusion_tag('news_summary_item.html')
def get_news_items():
    news_root = get_page_from_path('news')
    newsitems = news_root.children.filter(published=True)
    return {'newsitems':newsitems}

这是它使用的模板:
{% load cms_tags menu_tags %}
<ul>
{% for item in newsitems %}
    <li><a href="/{{ item.get_path }}">{{ item.get_title }}</a>
        {% for placeholder in item.placeholders.all %}
            # {% show_placeholder placeholder.slot item current_language %} #
        {% endfor %}
    </li>
{% endfor %}
</ul>

任何人都可以帮助在这里获取占位符内容吗?理想情况下,id 希望能够通过 truncatewords_html 传递它来获得摘要,但也可以通过其他方式获得相同的效果。

感谢任何提示/指针!

最佳答案

我必须在一个项目中索引 CMS 内容,我得到每个占位符的内容,占位符的内容存储在附加的插件中

如何在 View 中获取 CMSPlugin 的内容?

from cms.models import CMSPlugin

plugin = CMSPlugin.objects.filter(plugin_type='TextPlugin')[0]  # Get first text plugin
# This return the body/content of the plugin:
plugin_content = plugin.get_plugin_instance()[0].body 

如果您想管理其他插件,如 PicturePlugin你可以得到像这样的“alt”文本:
plugin_picture_content = plugin.get_plugin_instance()[0].alt

如何在模板中获取 CMSPlugin 的内容?
# plugin_object containing a CMSPlugin
{{plugin_object.get_plugin_instance.0.body}}

我想当你想获取内容时,我们正在谈论 TextPlugin ,这里要小心,因为只有插件类型TextPlugin具有属性 body , PicturePlugin具有属性 altLinkPlugin具有属性 href ETC...

适合您问题的解决方案

您正在循环 占位符 , 所以你需要得到 所有插件对于每个占位符并获取每个插件的内容,因为我之前提到的占位符的内容存储在附加到它的插件中(TextPlugin、PicturePlugin、LinkPlugin...)。
...    ...    ...
{% for placeholder in item.placeholders.all %}  # Loop over placeholders
    {% for plugin in placeholder.get_plugin_list %}  # Get plugins for each placeholder
        {{plugin.get_plugin_instance.0.body|striptags}}
    {% endfor %}
{% endfor %}
...    ...    ...

并确保您只显示TextPlugin的内容而不是你可以做的其他插件:
...    ...    ...
{% for placeholder in item.placeholders.all %}  # Loop over placeholders
    {% for plugin in placeholder.get_plugin_list %}  # Get plugins for each placeholder
        {% if 'TextPlugin' in plugin.plugin_type %}
            {{plugin.get_plugin_instance.0.body|striptags}}
        {% endif %}
    {% endfor %}
{% endfor %}
...    ...    ...

关于django-cms "summary view"从多个页面聚合内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16458403/

相关文章:

python - Django 填充下拉菜单,包含多对多数据库的选择

python - 神秘的 "cannot import name"异常

python - Django 管理员。在日期后禁用 `list_editable` 字段进行编辑?

python - 在一定数量的变量之后更改列表输出

python - Django 。 TemplateDoesNotExist 在自定义小部件的情况下

python - 带有预装依赖项的 pip 包安装

django - 如何在 Django-CMS 中停用 WYMeditor 以仅使用纯 HTML?

jquery - Django - Ajax HttpResponse 延迟

python - 在 Scrapy 中访问 django 模型

django - 无法在 Django 中生成外键字段