5

I am new to web-development using Flask and Jinja2 templates. One column in a row of my HTML table in the template is:

<td><a> href="/plot?label={{stats[0]}}">{{stats[0]}} </a></td>

stats[0] is a variable which is a string and might contain an '&' e.g. "Eggs & Spam". Now in the view (views.py):

@app.route("/plot", methods = ["GET", "POST"])
@login_required
def on_plot():
    data = request.args
    label_name = data['label']

In this case I get data as ImmutableMultiDict([(' Spam', u''), ('label', u'Eggs ')]) which is not correct. Instead I want ImmutableMultiDict([('label', u'Eggs & Spam ')])

So how do I handle this case ? I tried doing {{stats[0]|escape}} but it doesn't work.

codegeek
  • 32,236
  • 12
  • 63
  • 63
Lyman Zerga
  • 1,415
  • 3
  • 19
  • 40

1 Answers1

4

You want to build the URL from the view instead, using url_for:

<td><a> href="{{ url_for('on_plot', label=stats[0]) }}">{{stats[0]}} </a></td>

The url_for() method will build a query string for you and escape the ampersand appropriately.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Sorry, I deleted my previous comment as it did not apply. Even though I happened to use Flask, neither JS nor HTML is generated (only the web service is), so I found what I needed in the following question, which has nothing to do with Flask and everything with URL encoding in JS: http://stackoverflow.com/questions/332872/how-to-encode-a-url-in-javascript – Leonid Jan 20 '14 at 00:27