简体   繁体   中英

How to compare jinja expression in javascript with escape sequences string?

I am working on a django project which uses jinja as a templating language. My problem:

I have a li tag inside html:

<li onclick="toggle_size_selection('{% if \'/\' in co.2 %}{{ co.1 }}{% else %}{{co.2}}{% endif %}')">Point1</li>

It returns me the following error in response when I visit the url:

TemplateSyntaxError at /detail-page/
Could not parse the remainder: '\'/\'' from '\'/\''

How to properly write this expression?

"toggle_size_selection('{% if \'/\' in co.2 %}{{ co.1 }}{% else %}{{co.2}}{% endif %}')"

I assume you want to pass a single quote string to toggle_size_selection for which you can replace the outermost single quote with &#39; thus Django template not evaluating it.

<li onclick="toggle_size_selection(&#39;{% if '/' in co.2 %}{{ co.1 }}{% else %}{{co.2}}{% endif %}&#39;)">Point1</li>

Reference: Django Escaping

I think what you're trying do is easier to do with javascript itself. You can do variable assignment like this var co_2 = '{{ co.2 }}' in javascript and then create a simple if else to do what you're looking for.

这是我在 Rishabh Chvhan 的回答之后找到的工作解决方案:我刚刚&#39 with &#39;替换&#39 with &#39;

<li onclick="toggle_size_selection(&#39;{% if '/' in co.2 %}{{ co.1 }}{% else %}{{co.2}}{% endif %}&#39;)">Point1</li>

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