javascript文件的变色龙模板? [英] Chameleon templates for javascript files?
问题描述
我正在开发一个简单的金字塔应用程序,我正在使用JQuery来执行AJAX请求。我到目前为止在变色龙模板中有我的javascript代码。现在我想将我的javascript提取到另一个位置(例如作为静态资源)。
I am developing a simple pyramid application where I am using JQuery to do AJAX requests. I have until now had my javascript code within my chameleon templates. Now I want to extract my javascript into another location (e.g. as static resources).
我的问题是我发现我的javascript代码依赖于动态生成的内容,如下所示: / p>
My problem is that I find my javascript code relies on dynamically generated content like so:
$.post("${request.route_url('my_view')}",{'data': 'some data'}, function(html){
$("#destination").html(html);
});
动态元素为:
"${request.route_url('my_view')}"
这是在模板中调用请求对象的route_url方法。
Which is calling the route_url method of the request object within the template.
是否存在将这些javascript文件分离到自己的模板并为它们提供路径和视图的可识别模式或者我只是将我的javascript保存在我的页面模板中?
Is there a recognised pattern for separating such javascript files into their own templates and providing routes and views for them or do I simply keep my javascript in my page template?
推荐答案
是的;您通常会将特定于上下文的信息(如扩展路径)放入模板中,并从(静态)JavaScript库中访问此信息。
Yes; you generally put context-specific information like expanded routes into the templates and access this information from your (static) JavaScript libraries.
包含上下文信息可以通过多种方式完成,取决于口味:
Including the context info can be done in various ways, depending on taste:
-
您可以在生成的HTML中的标签上使用数据属性:
You could use a data attribute on a tag in your generated HTML:
<body data-viewurl="http://www.example.com/route/to/view">
...
</body>
然后,在静态JS代码中加载jQuery .data()
功能:
which you then, in your static JS code load with the jQuery .data()
function:
var viewurl = $('body').data('viewurl');
使用虚构的 LINK标签关系,包括文档头中的链接:
Use a made-up LINK tag relationship to include links in the document head:
<head>
<link rel="ajax-datasource" id="viewurl"
href="http://www.example.com/route/to/view" />
...
</head>
可以使用 $('link#viewurl')检索。 ('href')
,或 $('link [rel = ajax-datasource]')。attr('href')
。这仅适用于URL信息。
which can be retrieved using $('link#viewurl').attr('href')
, or $('link[rel=ajax-datasource]').attr('href')
. This only really works for URL information.
直接在模板中生成JS变量,以便从静态代码中引用:
Generate JS variables straight in your template, to be referenced from your static code:
<head>
...
<script type="text/javascript">
window.contextVariables = {
viewurl = "http://www.example.com/route/to/view",
...
};
</script>
</head>
这些变量可直接与 contextVariables.viewurl $ c $相关联c>。
这篇关于javascript文件的变色龙模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!