0

I am sending a variable names = "['name1', 'name2', 'name3']" as String to an HTML file from my method in views.py along with other information.

When I tried to split the string names with names.split() as:

{% for name in names.split(',') %}
 {{ name }}
{% endfor %}

then I am facing this TemplateSyntaxError

Could not parse the remainder: '(',')' from 'share.share_per_person.split(',')'

When I tried to print the string as

{{ names }}

then output is ['name1', 'name2', 'name3']

I want to display individual names on screen.

James Z
  • 12,209
  • 10
  • 24
  • 44
Bharanidhar Reddy
  • 420
  • 1
  • 4
  • 12
  • 1
    Can you explain why you are sending this string that looks like a list in the first place? Where did you get it from? And why can't you do this conversion in the view? – Daniel Roseman Apr 07 '18 at 20:56
  • Why don't you render `template` with `render()` method with `context` , so you can easily loop through it ? – Cuong Vu Apr 07 '18 at 20:57
  • @DanielRoseman I am getting this data from local Database in which I used a column "names" to store list of names as a string in database. – Bharanidhar Reddy Apr 07 '18 at 21:35
  • @VuHuuCuong I used render from my view to call html file as return render(request, 'app/main.html', {'names': names}). Is this what you asked? I dont have knowledge on what a context is. – Bharanidhar Reddy Apr 07 '18 at 21:43
  • Convert to a proper list in the view. See https://stackoverflow.com/a/1894293/4872140 for how. – AMG Apr 08 '18 at 02:59

1 Answers1

0

use something like the following in your view to convert that string from your database to a proper list using abstract syntax tree method literal_eval.

from django.shortcuts import render
import ast

def sample_request(request):

    names = "['name1', 'name2', 'name3']"

    # abstract syntax tree
    # https://docs.python.org/3.6/library/ast.html
    names_list = ast.literal_eval(names)

    context = {'names': names_list,
               'some_other_var': 'value',
               }
    return render(request, 'dashboard/index.html', context)

then in your template you should be able to do the normal {% for name in names %} {{ name }}<br /> {% endfor %} credit to https://stackoverflow.com/a/1894293/4872140

AMG
  • 1,606
  • 1
  • 14
  • 25