【问题标题】:django dynamic inclusion tagdjango 动态包含标签
【发布时间】:2014-07-29 05:25:41
【问题描述】:

我正在尝试向模板添加一些图片库,但页面上图库的位置需要由用户定义。有时它会在文本的顶部,有时在末尾,有时在页面文本的中间。在文本字段中,用户将添加这一行#foto,并根据我需要渲染画廊的那一行的位置。例如:

some paragraph written by user in the text field...

#foto

some another paragraph written by user ...

现在最简单的方法是在视图中将#foto 替换为包含标签。比如:

foto = "{% include 'includes/gallery.html' %}"
xx = "#foto"
post.text = post.text.replace(xx, foto)

但是这个例子不起作用,因为包含标签不能以这种方式调用。它呈现为纯文本 {% include 'includes/gallery.html' %}。可以做些什么来在 #foto 文本的位置上按预期呈现包含标记。

【问题讨论】:

    标签: django django-templates django-views django-filter


    【解决方案1】:

    在您的视图中将照片分配给渲染的模板:

    ...
    from django.template.loader import render_to_string
    """
    Get the items from the model, define your query
    """
    gallery = GalleryModel.objects.all()
    """
    Render gallery template and assign to foto, which then you
    can inject in the basic template
    """
    foto = render_to_string('includes/gallery.html', {'gallery': gallery})
    ...
    

    然后在您的模板中:

    {{ foto }}
    

    【讨论】:

    • 没有 petkostas 画廊不能以这种方式调用 {{ post.text }} 是一个返回文本的标签,并且画廊需要位于文本中`#foto`字的位置.
    • 因此实现上述内容并替换原始帖子中的文本,render_to_string 就是您要查找的内容。获取 post.text,用 foto 渲染的模板替换。
    猜你喜欢
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2017-04-06
    • 1970-01-01
    • 2012-12-22
    • 2012-07-05
    • 1970-01-01
    相关资源
    最近更新 更多