如何在Django模板页面中设置href

时间:2020-06-18 18:11:32

标签: python django web-applications

我是Django的新手。我的首页模板看起来像这样:

{% block content %}
    {% for link in embededLinks %}
    <div class="row justify-content-center">
        <blockquote class="twitter-tweet">
            <p lang="en" dir="ltr">Do you get the impression that the Supreme Court doesn’t like me?</p>
            &mdash; Donald J. Trump (@realDonaldTrump) 
            <a href="{{%link%}}">June 18, 2020</a>
        </blockquote> 
        <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
    </div>
    {% endfor %}
{% endblock %}

循环遍历了我的网站的链接列表,以正确显示嵌入式推文。此html将放入我拥有的基本模板中。唯一的问题是我在此行出现错误:

<a href="{{%link%}}">June 18, 2020</a>

href链接是在另一个python文件中生成的,类型为str。唯一的事情是我不确定如何使用Django设置href。

2 个答案:

答案 0 :(得分:2)

我没有使用Django的经验,但是与Flask在一起。

显示变量是{{ link }}而不是{{%link%}}吗?

答案 1 :(得分:0)

在Django中,您可以添加链接,例如href =“” {%url'url_name'%}“”。 请记住,您必须给url /路径指定名称才能使用它。 例如:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
# let's say this index view renders home page and name is given 'index' to this urls(this name will be used for recalling urls paths and it can be anything).
]
Then your link looks like href = "{% url 'index' %}" . For more info check , 
https://docs.djangoproject.com/en/3.0/intro/tutorial03/
相关问题