开发者

Passing parameters to the Javascript code on a page using django templates?

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(func开发者_如何学JAVAtion() {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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜