在 Django url 模板标签中获取 javascript 变量的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17832194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:47:57  来源:igfitidea点击:

Get javascript variable's value in Django url template tag

javascriptdjangourl

提问by Mike Lee

It is known that there's a DRY way of directing to an URL by using django template tag "url", say

众所周知,有一种使用 django 模板标签“url”定向到 URL 的 DRY 方式,例如

{% url "someview" arg1=X %}

Here, I want "X" to be the value of a javascript variable, say tmp. But the following doesn't work

在这里,我希望“X”是一个 javascript 变量的值,比如tmp. 但以下不起作用

<script>
    ...{% url "someview" arg1=tmp %}...
</script>

How should I get the value inside a template tag?

我应该如何获取模板标签内的值?

回答by Mike Lee

I found a trick that might work under most circumstances:

我发现了一个在大多数情况下可能有效的技巧:

var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, tmp.toString());

It's clean, and it doesn't break DRY principle.

它很干净,而且不违反 DRY 原则。

回答by Olfredos6

Just making it clear so next readers can have a comprehensive solution. In regard to the question, this is how I used Mike Lee solution for an example case which is redirecting with Javascript to a new page with a parameter in a variable named tmp:

只是说清楚,以便下一位读者可以有一个全面的解决方案。关于这个问题,这是我如何将 Mike Lee 解决方案用于示例案例,该案例使用 Javascript 重定向到一个新页面,该页面的参数位于名为tmp的变量中:

window.location = "{% url 'your_view_name' 1234 %}".replace(/1234/, tmp.toString());

回答by Moayyad Yaghi

one easy way to do this is

一种简单的方法是

<div id="test" style="display: none;">
 {% url 'some_url:some_sub_url'%}
</div>


<script>
  url_mask = $( "#test" ).html()
</script>

回答by Brandon

I don't think you'll be able to use a named argument to {% url %}from JavaScript, however you could do a positional argument or querystring parameter:

我认为您不能使用{% url %}来自 JavaScript的命名参数,但是您可以使用位置参数或查询字符串参数:

<script type="text/javascript">
    var tmp = window.location.hash, //for example
        url = {% url '[url_name]' %} + tmp + '/';
</script>

But, you could only do that once, when the template is initially rendered.

但是,您只能在最初呈现模板时执行一次。

回答by Victor Tax

var name = "{% url 'your_view_name' pk=0 %}".replace('0', name_variable);

回答by santiagopim

Similar solution with concatinstead of replace, so you avoid the idclash:

类似的解决方案,concat而不是replace,这样你就可以避免id冲突:

var pre_url = "{% url 'topology_json' %}";
var url = pre_url.concat(tool_pk, '/', graph_depth, '/');

But you need a non-parameter url to keep Django pleasant with the pre_urlbecause the loading-time evaluation, my urls.pyis:

但是你需要一个非参数 url 来让 Django 满意,pre_url因为加载时间评估,我urls.py是:

urlpatterns = [
    url(r'^topology_json/$',
        views.topology_json,
        name='topology_json'),
    url(r'^topology_json/(?P<tool_id>[0-9]+)/(?P<depth>[0-9]+)/$',
        views.topology_json,
        name='topology_json'),
    ...
]

And parameters in view have suitable default values, so views.py:

并且视图中的参数具有合适的默认值,因此views.py

def topology_json(request, tool_id=None, depth=1):                                             
    """                                                                                        
    JSON view returns the graph in JSON format.                
    """                                                                                        
    if tool_id:                                                                                
        tool = get_object_or_404(Tool, pk=tool_id)                                             
        topology = get_graph(str(tool), int(depth))                                            
    else:
        ...      

Django yet 1.11 here.

Django 1.11 在这里。