【问题标题】:Django: is this possible to call view from template like ASP.NET MVCDjango:这可以从像 ASP.NET MVC 这样的模板调用视图吗
【发布时间】:2015-03-24 21:21:41
【问题描述】:

我正在开发 Django 框架。我正在寻找从模板调用视图的函数。

在 Asp.NET MVC 中,我们可以通过这种方式从视图(模板)调用操作(视图)。

@Html.Action("Controller Name", "Action Name") or

@Html.Action("Action Name")

简单来说我想在其他模板中获取模板html。

def index(request):
    return render(request, 'index.html')

def my_list(request):
    q = MyModel.objects.all()
    return render(request, 'mylist.html',{'my_list':q})

index.html

<html>
<head></head>
<body>

#want to call my_list view

</body>
</html>

mylist.html

<script>
    #lot of script here
</script>

{% for record in my_list %}
    <p>{{ record }}</p>
{% endfor %}

我从搜索中获得的解决方案使用 html 表单或 jquery 发布或获取请求。

my_list 视图包含查询集对象。我不想直接在索引视图中调用此查询。这是部分视图。

此类问题有哪些解决方案?

谢谢

【问题讨论】:

    标签: asp.net-mvc django python-3.x


    【解决方案1】:

    这是可行的,但您似乎正在尝试重新发明inclusion template tags

    @register.inclusion_tag('mylist.html')
    def my_list():
        q = MyModel.objects.all()
        return {'my_list': q}
    

    然后在index.html:

    <html>
        {% load my_tags %}
        <head></head>
        <body>
            {% my_list %}
        </body>
    </html>
    

    【讨论】:

    • 哦,太好了。我怎么傻!我已经阅读了这篇文章,但无法理解该功能:(
    • 还有两件事要问。当我加载 html 时,Javascript 也能正常工作吗?我想覆盖父页面块标签。这在 my_list 模板中可行吗?谢谢
    • mylist.html 模板将作为字符串呈现并“粘贴”到index.html。所以你的 JS 会像在 index.html 中一样工作。
    • 而且你不能从mylist.html覆盖index.html的父页面块。
    【解决方案2】:

    使用include 标签。 您可以使用with 语句将上下文传递给模板。
    这与@Html.Action 不同,但非常相似。
    https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#include

    【讨论】:

      猜你喜欢
      • 2022-07-14
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多