需要在django模板中将字符串转换为int [英] Need to convert a string to int in a django template
问题描述
我正在尝试将url参数传递给这样的django模板...
I am trying to pass in url parameters to a django template like this...
response = render_to_string('persistConTemplate.html', request.GET)
这是来自我的views.py文件的调用行。 persistConTemplate.html是我的模板和请求的名称.GET是包含url参数的字典。
This the calling line from my views.py file. persistConTemplate.html is the name of my template and request.GET is the dictionary that contains the url parameters.
在模板中,我尝试使用这样的参数之一...
In the template I try to use one of the parameters like this...
{% for item in (numItems) %}
item {{item}}
{% endfor %}
numItems是url参数之一我按照我的请求发送...
numItems is one of the url parameters that I am sending in my request like this...
http:/someDomain/persistentConTest.html/?numItems=12
当我尝试上面的for循环时,我得到一个这样的输出....
When I try the for loop above, I get an output like this....
image 1 image 2
image 1 image 2
我期待着喜欢看单词图像打印12次...
I am expecting and would like to see the word image printed 12 times...
图像1图像2图像3图像4图像5图像6图像7图像8图像9图像10图像11图像12
image 1 image 2 image 3 image 4 image 5 image 6 image 7 image 8 image 9 image 10 image 11 image 12
任何人都可以告诉我我出了什么问题?
Can anyone please tell me what I am going wrong?
推荐答案
是的,这个地方在视图中。
Yes, the place for this is in the view.
我觉得上面的例子不会工作 - 你不能迭代一个整数。
I feel like the above example won't work -- you can't iterate over an integer.
numItems = request.GET.get('numItems')
if numItems:
numItems = range(1, int(numItems)+1)
return direct_to_template(request, "mytemplate.html", {'numItems': numItems})
{% for item in numItems %}
{{ item }}
{% endfor %}
这篇关于需要在django模板中将字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!