简体   繁体   中英

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. 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:

{% 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. Try:

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

Try this instead of the above jinja file. If you need just values of var , and if var is dictionary, then this below code would work for you.

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

you have error in view, you need to pass context as dictionary from 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:

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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