如何保存Django“带有”模板标签值并在其他模板中重复使用?

时间:2019-07-23 08:38:22

标签: django django-templates

我有一个模板标记,可以从URL读取值。例如 搜索的词是癌症。搜索后,显示的下一页将带有搜索词:癌症。而且,我希望有价值的癌症能出现在我的所有网页中,直到用户进行新搜索为止。

我以这种方式工作的页面: Search.html> display.html> Explore.html

Search.html是用户输入要搜索的内容的地方。

我有一个searchedterms.html,它包含在所有3个模板中,并包含要从URL读取的Javascript代码。

通过使用JavaScript代码,我设法显示了搜索词:display.html中的癌症,但explorer.html中的值为空。我希望能够将“癌症”保存到标签并在其他模板中使用它。

?conditions=cancer

在search.html中:

<input required="" type="text" name="conditions">

在display.html中:

{% with searched_terms='searchedterms.html' %}
{% include searched_terms %}
{% endwith %}

在explorer.html中:

{% with searched_terms='searchedterms.html' %}
{% include searched_terms %}
{% endwith %}

在searchedterms.html中:

<div id="searched" class="container"></div>
<script type="text/javascript">
 var urlParams = new URLSearchParams(window.location.search);

  function getUrlParameter(name) {
      name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
      var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
      var results = regex.exec(location.search);
      return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  };
  var condition = getUrlParameter('conditions');

  document.getElementById("searched").innerHTML = "Searched Terms: " + condition;

</script>

实际结果:癌症出现在display.html中,但没有出现在explorer.html中。刷新display.html时,“癌症”也消失了。

期望的结果:癌症出现在display.html和Explore.html中,直到用户开始新的搜索为止。

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找Django Inclusion tag

如下所示在 templatetags 中注册您的标签:

@register.inclusion_tag('searchedterms.html')
def searched_terms(query):
    return {
        'query': query
    }

,现在在您的 searchedterms.html 文件中:

<div>
your searched query is: {{ query }}  {# display your query here #}
</div>

对于基于类的视图:

在您的 Search.html > display.html > explore.html 文件中:

{% load tags %}

{% block content %}

{% searched_terms view.kwargs.conditions %} {# here you pass your kwargs from url #}
<div>some of your existing code. </div>

{% endblock %}

Access kwargs from a URL in a Django template

解释了view.kwargs.conditions的工作方式

对于功能视图:
如果要从功能视图中将url kwargs放在模板中,则可以在视图中获取url kwargs并将其作为上下文数据传递:

def search_view(request, **kwargs):
    """
    your existing codes
    """
    context = {'conditions': kwargs.get('conditions')}
    return render(request, 'search.html', context)

在模板中使用request从url访问:
如果您要从模板中的url访问数据,则也可以根据您要访问数据的方式使用request.GETrequest.POST,如 Search.html > display.html > explore.html 文件:

{% load tags %}

{% block content %}

{% searched_terms request.GET.conditions %} {# here you access data from url #}
<div>some of your existing code. </div>

{% endblock %}

您可以查找django文档HttpRequest objects,以获取request可以访问的内容。