简体   繁体   English

在Django的html模板中传递变量

[英]Pass a variable in an html template in django

I need to create in a html django template a form with a select dinamically created: I read values from a txt file and I store it in a dict, when I call the render to response I pass this dict but when I try to print its values in the template it doesn't print anything. 我需要在html django模板中创建一个具有动态创建选择的表单:我从txt文件中读取值,并将其存储在dict中,当我调用渲染响应时,我通过了该dict,但是当我尝试打印它时模板中的值不会打印任何内容。 This is my views: 这是我的看法:

def home(request):

   i=0
   d = {}
   with open("static/my_file.txt") as f:
      for line in f:
        key=i
        val = line.rstrip()
        d[int(key)] = val
        i=i+1

   return render_to_response('home.html', var=d)

and this is the print in the html template: 这是html模板中的打印内容:

{% for val in var %}
   {{ val.value }}
{% endfor %}

Can help me? 可以帮我?

The Django documentation for for -loops in templates shows that the syntax for dicts is slightly different. 模板for -loopsDjango文档显示,字典的语法略有不同。 Try: 尝试:

{% for key, value in var.items %}
    {{ value }}
{% endfor %}

Try this instead of the above jinja file. 试试这个代替上面的jinja文件。 If you need just values of var , and if var is dictionary, then this below code would work for you. 如果您只需要var值,并且var是字典,那么下面的代码将为您工作。

{% for val in var.values() %}
   {{ val }}
{% endfor %}

you have error in view, you need to pass context as dictionary from django.shortcuts import render 您的视图有错误,您需要从django.shortcuts import render将上下文作为字典传递

def home(request):

   i=0
   d = {}
   with open("static/my_file.txt") as f:
      for line in f:
        key=i
        val = line.rstrip()
        d[int(key)] = val
        i=i+1

   return render(request,'home.html', {'var':d})

If you want to pass just the variable or all variable available (local variable) in the view.py to your template just pass locals() in your case should be: 如果您只想将view.py中的变量或所有可用变量(局部变量)传递给模板,只需将locals()传递给您即可:

view.py: view.py:

def home(request):

   i=0
   d = {}
   with open("static/my_file.txt") as f:
      for line in f:
        key=i
        val = line.rstrip()
        d[int(key)] = val
        i=i+1

   return render('home.html', locals())

template: 模板:

{% for key,value in d.items %}
   {{ value }}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM