Django 将变量传递给模板

新手上路,请多包涵

嗨谢谢你的帮助,我的编码很差。

要点:我正在做一个 Django 项目,将数据从数据库传递到前端;但是现在我什至无法将 Django 的任何视图传递到模板中,我怀疑我传递了错误的变量类型;请对您的想法发表评论。

这是我在 views.py 上的代码:

 from django.shortcuts import render

def index (requset):
    return render(requset,'myapp/index.html') # link to be able open frountend

def testdex(requset):
    text = "hello world"
    context ={'mytext' : text }
    return render(requset,'myapp/inculdes.html', context)

所以我的变量将被传递到扩展到索引页面的 inculdes

这是我在 inculdes.html 中的代码:

 {% exntends "myapp/index.html" %}

{% block includes %}
{{ mytext }}
{% endblock includes %}

这是我在 index.html 上的代码:

 <body>
{% block includes %} {% endblock includes %}
</body>

再次感谢您给我时间来帮助我,如果能给我写一些代码,我将不胜感激,因为我会尝试整整一周来解决这个问题

原文由 Rookies DJ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 375
2 个回答

你可以尝试这样的事情

视图.py

 from django.template.response import TemplateResponse

def testdex(requset, template_name="myapp/inculdes.html"):
    args = {}
    text = "hello world"
    args['mytext'] = text
    return TemplateResponse(request, template_name, args)

包括.html

 {% extends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}

并确保您已在 settings.py 中设置模板路径

原文由 Ajay Kumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

当您执行 {% block content %}{% endblock content %} 时,您是在告诉 Django 您希望能够覆盖此部分。请注意单词内容可以是任何内容以反映您要覆盖的内容。

当您执行 {{ variable }} 时,您是在告诉 Django 您想要传递一个上下文。在此示例中,我要传递的变量称为 Title 作为键,Portfolio 作为值。上下文是您在 views.py 中传递的字典,如下所示:

 def portfolio_home(request):
    return render(request, 'portfolio/work.html', {'title': 'Portfolio'})

假设我想将上下文(或变量)传递到我的基本模板中。在这个例子中,我想在我的基本模板的 head 部分的 title 标签中传递 title 。

base.html 的 html 文件中,你需要有这样的东西:

 <!DOCTYPE html>
<html lang="en">

{% load staticfiles %}

    <head>
        <title>{{ title }}</title>
        ...........
    </head>
</html>

在我的项目和其他我想将标题传递给它的应用程序的 urls.py 中,我应该像这样创建视图:

 def portfolio_home(request):
    return render(request, 'portfolio/work.html', {'title': 'Portfolio'})

原文由 azmirfakkri 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题