使用django模板将参数传递到页面上的Javascript代码? [英] Passing parameters to the Javascript code on a page using django templates?

查看:203
本文介绍了使用django模板将参数传递到页面上的Javascript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Django应用程序,它有各种不同资产类型的视图。我有各种jQuery函数,键入资产类型名称,所以当我使用django模板生成页面时,我使用模板变量来填充javascript代码中的资产类型参数...

  $(document).ready(function()
{
$(。project)click(function(){return FiltersChanged('{{asset_type}}',$('#filter_entry')。val());});
});

我在应用程序中使用了这种范例,对我来说似乎有点尴尬,我发现我在不同的模板文件中创建了很多重复的代码,因为我需要填写{{asset_type}}变量,我想能够减少重复,而不需要生成



所以,有没有更好的方法来做,不需要在每个页面中复制代码?

解决方案

对于常用的值,一个选项是让模板的某些部分将它们转储到全局可用的对象中,然后是脚本可以访问这些值。例如,你可以这样做:

 < script> 
body.data('assetInfo',{
'type':'{{asset_type}}',
// ...
});
< / script>

然后,您的脚本可以在身份标签上的assetInfo数据元素需要时东东。当您的脚本可以从服务器端代码中释放时,这样很好,因为您可以让客户端缓存它们。


I have a simple Django app that has a variety of views of various different asset types. I have various jQuery functions that key off the asset type name and so when I generate the page using the django template I use a template variable to fill in the asset type parameter in the javascript code...

$(document).ready(function() 
{ 
    $(".project").click(function() {return FiltersChanged('{{ asset_type }}', $('#filter_entry').val());});
});

I'm using this kind of paradigm a lot in the app and it seems a little awkward to me, I'm finding that i'm creating a lot of duplicate code in different template files simply because I need to fill in that {{asset_type}} variable and i'd like to be able to reduce the duplication and not need to generate that code in the template every time.

So, is there a better way to do this that doesn't require duplicating code in each page?

解决方案

For commonly-used values like that, one option is to have some part of your template dump those into a globally-available object, and then your scripts can access the values that way. For example, you could do something like this:

<script>
  body.data('assetInfo', {
    'type': '{{ asset_type }}',
    // ...
  });
</script>

Then your scripts can just go to the "assetInfo" data element on the body tag when they need that stuff. It's nice when your scripts can be free from server-side code because you can then let the clients cache them.

这篇关于使用django模板将参数传递到页面上的Javascript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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