Django 模板引擎和外部 js 文件
我正在编写一个 Google 应用程序引擎应用程序,显然默认的 Web 应用程序框架是 Django 的子集。因此,我正在使用它的模板引擎。
我的问题是,如果我说出以下代码:
template_values = {
'first':first,
'second':second,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
并且我想在index.html中的外部包含的javascript文件中引用模板值first
,我是否只需继续使用{{first我会在index.html本身中使用,或者我是否需要以某种方式告诉框架有关example.js的信息,以便它知道替换那里的引用?
I'm writing a Google app engine app and obviously the default web app framework is a subset of Django. As such I'm using it's templating engine.
My question is if I have say the following code:
template_values = {
'first':first,
'second':second,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
And I want to reference the template value first
in an externally included javascript file from index.html, do I just continue with the {{ first }}
usage I'd go with in index.html itself or do I need to tell the framework about example.js somehow too so that it knows to replace the reference there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将值插入 javascript 可能是一个坏主意;对于静态脚本并让它从 DOM 中获取数据(假设它是您正在渲染的 HTML 页面的一部分)或使用 AJAX 调用从服务器获取必要的数据不是更有意义吗?
Inserting the value into the javascript is probably a bad idea; wouldn't it make more sense for the script to be static and to have it grab the data either out of the DOM (assuming it's part of the HTML page you're rendering) or get the necessary data from the server using an AJAX call?
免责声明:我对应用程序引擎的了解有限,因此这个答案可能无法满足您的目的。
在 Django 中,如果您需要能够将变量从视图传递到 JS 文件,则必须确保该文件由模板引擎解析。换句话说,该文件必须由 Django 提供。这意味着,例如,如果您在由 Nginx 提供服务的
media
目录中有一个 JS 文件,您将无法在其中使用模板变量。我希望同样的情况也适用于应用程序引擎。但随后请参阅免责声明。我可能完全错了:P
Disclaimer: my knowledge of app engine is limited so this answer may not serve your purpose.
In Django if you need to be able to pass variables from a view to a JS file you will have to ensure that the file is parsed by the template engine. In other words the file has to be served by Django. This means for e.g. that if you have a JS file in a
media
directory that is served by say, Nginx, you will not be able to use template variables in it.I would expect the same to apply for app engine. But then see the disclaimer. I might be totally wrong :P