MrC*_*ooL 2 javascript django jquery django-templates
当我做这样的事情时:
$("#show").click(function(){
{% for p in collection %}
options.push({
'href' : '{{ p.id }}',
});
{% endfor %}
});
Run Code Online (Sandbox Code Playgroud)
我可以检索Django模板变量的值.
但是,当我试图在其他方面做的时候:
$('[name=test]').live('click', function() {
alert('{{ current_state }}');
var msg = '<div class="userName"> {{ current_user }} </div>';
alert('Message' + msg);
});
Run Code Online (Sandbox Code Playgroud)
我无法从中检索Django模板变量的值.
从这里出了什么问题?我有时会在javasript/jQuery中检索Django模板变量.
编辑
当我在其他所有内容上执行以下行时,整个javasript都无法正常工作.知道为什么吗?
$('body').data('current_user_id', {{ current_user_id }});
$('body').data('current_user', {{ current_user }});
Run Code Online (Sandbox Code Playgroud)
通常,JS文件是完全静态的,因此,您不能将Django变量插入其中 - 它不能像那样工作.
你可以采取的一种方法是让Django"停放"渲染的HTML模板中JS所需的变量,然后你可以抓取它们并根据需要在JS代码中使用它们
例如,在您的示例中使用javascript的模板中,添加:
<script type="text/javascript">
// attach variables from Django to the body node of the document
$('body').data('current_state', {{current_state}});
$('body').data('current_user', {{current_user}});
</script>
Run Code Online (Sandbox Code Playgroud)
然后在你的JS中,从数据映射中提取值:
$('[name=test]').live('click', function() {
alert($('body').data('current_state'));
var msg = '<div class="userName">' + $('body').data('current_user') + '</div>';
alert('Message' + msg);
});
Run Code Online (Sandbox Code Playgroud)
如果您不了解$ .data(),请阅读此内容
归档时间: |
|
查看次数: |
3597 次 |
最近记录: |