这是我当前拥有的 html 文件:
<!DOCTYPE html>
<html>
{{unit.unit_class}}
<div id="stats"></div>
<script>
var str ="", i;
for(i = 1; i<=99; i++)
{
str = str + "<p>level " + i + ": hp {{unit.hp_current}}</p>";
}
document.getElementById("stats").innerHTML = str;
</script>
</html>
for 循环 {{unit.hp_current}} 中的该位是十进制数。它的值当前设置为 0.00,它确实显示在我的页面上。我想知道我是否能够对双花括号内的这个变量进行算术运算。我尝试执行类似 {{unit.hp_current + 3}} 或 {{unit.hp_current}} + 3 的操作,以使程序显示 3.00 而不是 0.00,但它似乎不起作用。我需要在 view.py 中为此创建一个函数吗?
最佳答案
不,django模板语言不支持变量操作。您需要在代码中计算值,然后将它们传递给模板。另一种方法是在模板中使用函数,它将计算您需要的值:
When the template engine encounters a variable, it evaluates that variable and replaces it with the result. ...
If the resulting value is callable, it is called with no arguments. The result of the call becomes the template value. https://docs.djangoproject.com/en/3.0/ref/templates/language/
另一种选择是使用过滤器: https://docs.djangoproject.com/en/3.0/ref/templates/language/#filters
关于javascript - 你能对 html 脚本中双花括号内的变量进行数学运算吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59527137/