Karan
Karan

Reputation: 269

How to format such string?

I have a template to render but since it has some tags too it's getting difficult to access particular strings.The code goes like this:

   template="""
   <select>
   <option {% if record.views = '%s' %} selected {% endif %}>'%s'
   </select>
   """%(pop, pop)

Here I want the value of pop but it gives an error that:

    Caught TypeError while rendering: not enough arguments for format string

Any solution how can i access those string format. Thanks

Upvotes: 1

Views: 135

Answers (4)

Daniel Roseman
Daniel Roseman

Reputation: 599530

Seriously, don't try to preprocess the template language. It's a template language! It deals with this sort of thing!

Send selected_type into the template context, and do:

<option {% if record.views = selected_type %} selected {% endif %}>'{{ selected_type }}'

Upvotes: 4

TankorSmash
TankorSmash

Reputation: 12747

You're getting the error because Python is looking to fill all four of the % symbols. You need to escape them, by adding another % in front of them, like so:

template="""
   <select>
   <option {%% if record.views = '%s' %%} selected {%% endif %%}>'%s'
   </select>
   """%(pop, pop)

Upvotes: 0

uselpa
uselpa

Reputation: 18917

You need to double the % signs:

template="""
   <select>
   <option {%% if record.views = '%s' %%} selected {%% endif %%}>'%s'
   </select>
   """%(pop, pop)

yields

<select>
<option {% if record.views = '1' %} selected {% endif %}>'1'
</select>

for pop='1'

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304137

You should just double up the "%" to escape them

template="""
   <select>
   <option {%% if record.views = '%s' %%} selected {%% endif %%}>'%s'
   </select>
   """%(pop, pop)

Upvotes: 0

Related Questions