【问题标题】:how impelent php include (function) in django?django 中的 php 如何包含(函数)?
【发布时间】:2013-11-16 13:36:18
【问题描述】:

我知道一点 php 和 django。 当我用 php 写博客时,我为我的函数创建了一个文件。例如 10 个新帖子的功能、热门访问帖子的功能等。然后我在侧栏中使用这些功能。

使用标准视图时,我可以在 django 中得到相同的结果。但是当我使用通用类视图时,我不能将顶部或新帖子传递给模板? 有没有一种技术可以将它们包含到模板中并在模板中自动生成它们而不会将它们从视图中传递出去? 你如何在 django 中做这样的事情?

【问题讨论】:

标签: python django django-templates django-views


【解决方案1】:

看起来你想写template tags。例如:

@register.inclusion_tag('results.html')
def show_results(poll):
    choices = poll.choice_set.all()
    return {'choices': choices}

然后您可以通过在模板中写入来包含投票结果:

{% show_results poll %}

文档对此进行了更详细的解释,但可以使用类似的方法来显示热门帖子等。

【讨论】:

    【解决方案2】:

    简单的方法:

    {% include 'foo/bar.html' }
    

    如果需要参数化,需要声明一个包含模板标签并调用。

    【讨论】:

      【解决方案3】:

      Include Documentation Django

      {% include 'reusablecode.html' %}
      

      代码应该是这样的

      【讨论】:

        猜你喜欢
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 2011-03-31
        • 2012-01-25
        • 1970-01-01
        • 1970-01-01
        • 2011-05-01
        • 2020-12-24
        相关资源
        最近更新 更多