如何将javascript变量传递给django自定义过滤器 [英] How to pass javascript variable to django custom filter

查看:85
本文介绍了如何将javascript变量传递给django自定义过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在django模板代码中访问javascript变量,如下所示

Is there a way to access javascript variable in django template code as shown below

var tags_v1 = '{{ form.tags_1.value }}';
tags_v1 = tags_v1.split('{{ form.value_delim }}');
tags_v1 = tags_v1.map(function (item) { return '{{ $(item)|get_tag }}'; }) ;

我想将item的值作为变量传递给自定义过滤器get_tag / p>

I want to pass the value of "item" as variable to the custom filter "get_tag".

推荐答案

Django模板代码和浏览器JavaScript之间有一个重要区别,您似乎缺少:

There is an important distinction between Django template code and in-browser JavaScript that you seem to be missing:

Django模板是在服务器端构建的,而JavaScript在客户端执行。

这意味着模板代码总是在JavaScript之前执行(由服务器执行,在页面发送到客户端之前)。因此,绝对不可能按照您想要的方式混合JavaScript和Django代码。

That means that template code is always executed before JavaScript (as it is executed by the server, before the page is sent to the client). As a consequence it is absolutely impossible to mix JavaScript and Django code the way you want to.

例如,您似乎认为JavaScript循环中的Django代码将被执行多个倍。那当然不是这样。 Django代码在服务器端执行一次,而不用考虑后来在浏览器中执行的JavaScript(即完全不同的机器!)。对于Django,您的JavaScript代码只是一个无意义的文本。

For example you seem to think that Django code inside JavaScript loop would be executed multiple times. That of course is not true. Django code is executed once, on the server side, without any regard for JavaScript which is executed later in the browser (i.e. on a completely different machine!). For Django your JavaScript code is just a meaningless text.

所以,答案是:如果要拆分字符串并将Django过滤器应用于每个项目,则需要在Django的服务器端分割字符串。您不能在JavaScript中拆分它,然后在Django中操作生成的列表,因为Django的运行时间要早些,而在另一台计算机上。

So, the answer is: if you want to split a string and apply a Django filter to each item, you need to split the string on the server side in Django. You can't split it in JavaScript and then manipulate the resulting list in Django, because Django runs much earlier, and on a different computer.

这篇关于如何将javascript变量传递给django自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆