【问题标题】:How to set href in Django template page如何在 Django 模板页面中设置 href
【发布时间】:2020-06-18 18:11:32
【问题描述】:

我对 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。

【问题讨论】:

    标签: python django web-applications


    【解决方案1】:

    我没有 Django 经验,但我使用 Flask。

    显示变量会不会是{{ link }} 而不是{{%link%}}

    【讨论】:

      【解决方案2】:

      在 Django 中,您可以添加类似 href="{% url 'url_name' %}" 的链接。 请记住,您必须为 url/path 命名才能像这样使用它。 例如:

      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/
      

      【讨论】:

        猜你喜欢
        • 2015-01-18
        • 2013-06-06
        • 1970-01-01
        • 1970-01-01
        • 2011-12-16
        • 2014-10-07
        • 1970-01-01
        • 2014-06-09
        • 1970-01-01
        相关资源
        最近更新 更多