I’m creating a jQuery function on-the-fly with python:
jQuery = ("$('%(other_id)').click(function() { "
" if ($(this).is(':checked')) { "
" $('%(text_id)').show() "
" } "
" else {"
" $('%(text_id)').hide()"
" }"
" });")
I have to insert varibles into other_id and text_id. I see that $ sign is used for string templates (don’t know what it does though) So I escape them with double-$s($$)
jQuery = ("$$('%(other_id)').click(function() { "
" if ($$(this).is(':checked')) { "
" $$('%(text_id)').show() "
" } "
" else {"
" $$('%(text_id)').hide()"
" }"
" });")
However I can’t still format this:
>>> choice_id = 'foo'
>>> text_choice_id = 'bar'
>>> jQuery = ("$$('%(other_id)').click(function() { "
" if ($$(this).is(':checked')) { "
" $$('%(text_id)').show() "
" } "
" else {"
" $$('%(text_id)').hide()"
" }"
" });")
>>> jQuery %{'other_id' : choice_id, 'text_id' : text_choice_id }
Traceback (most recent call last):
File "<pyshell#123>", line 1, in <module>
jQuery %{'other_id' : choice_id, 'text_id' : text_choice_id }
ValueError: unsupported format character ''' (0x27) at index 15
after escaping single-quotes:
>>> jQuery = ("$$(\'%(other_id)\').click(function() { "
" if ($$(this).is(\':checked\')) { "
" $$(\'%(text_id)\').show() "
" } "
" else {"
" $$(\'%(text_id)\').hide()"
" }"
" });")
>>> jQuery %{'other_id' : choice_id, 'text_id' : text_choice_id }
Traceback (most recent call last):
File "<pyshell#125>", line 1, in <module>
jQuery %{'other_id' : choice_id, 'text_id' : text_choice_id }
ValueError: unsupported format character ''' (0x27) at index 15
can’t try string.format() because I have brackets inside the string. why am I keep getting ' as some unsupported format character?
You are missing the formatter type:
Note the
safter the parenthesis; you want to interpolate the values as strings. Here is a working version instead:Dollar symbols have no meaning in
%-style string formats and I’ve added the#id selectors for you. 🙂Personally, I would use
"""triple-quotes instead:Better still, put this into a Jinja template anyway (since you are using Flask) and render that instead:
where
toggle_field.jsis the Jinja template version of the jQuery snippet: