好的,所以我正在尝试使用 Django/Python 制作一个随机数生成器网页。我需要完成的是在我的 HTML 模板文件中以某种方式使用 python 代码,但我不知道如何做到这一点。
<h1 style="font-size:50px;line-height:20px;color:rgb(145,0,0);font- family: Arial Black, Gadget, sans-serif"></h1>
<h2 style="line-height:10px;color:rgb(140,140,140)"></h2>
<h3 style="font-size:40px;line-height:10px;font-family: Arial Black, Gadget, sans-serif"></h3>
<body style="background-color:rgb(255,239,154)"></body>
<!--Style placeholders-->
<h1 style="text-align:center;position:relative;top:20px">
Test Site
</h1>
<!--Reroll icon-->
<h1 style="text-align:center;position:relative;top:20px">
<input type='image' style='width:60px;height:56px;' src='../../static/polls/dice.png' alt='Re-roll'
onclick='location.reload();' value='Roll' /></h1>
原文由 Josh Silveous 发布,翻译遵循 CC BY-SA 4.0 许可协议
没有内置的方法可以做到这一点。如果您只需要一个随机值,一次,并且您不想从视图函数传递它——我想自定义模板标签就是这种方式。
在任何适当的应用程序中,创建一个文件
templatetags/random_numbers.py
(以及一个空的templatetags/__init__.py
如果您没有任何其他自定义模板标签)包含以下内容:然后,在您的模板中像这样使用它:
有关自定义标签的更多文档: https ://docs.djangoproject.com/en/1.11/howto/custom-template-tags/