简体   繁体   English

Mako模板中的JavaScript模板文字

[英]JavaScript template literals in a Mako template

I have a Mako file (that my Python server converts to HTML) that contains a script element with a JavaScript ES6 template literal. 我有一个Mako文件(我的Python服务器将其转换为HTML),该文件包含带有JavaScript ES6模板文字的脚本元素。 As both Mako and JS recognise ${..} , I am forced to write ${'${..}'} to get JS templating to work — ${{..}} akin to an f-string does nothing and I cannot find a | 由于Mako和JS都认识到${..} ,因此我不得不写${'${..}'}来使JS正常工作—类似于f字符串的${{..}}并没有任何作用,我找不到| flag that would escape it. 可以逃脱它的标志。 Say

<script>
//This is just an example
let entry = {title: '${some_py_value}'} //Mako templating
$('body').append(`${'${entry.title}'}`); //JS templating
</script>

This works but looks awkward, like something you'd see in Perl, to the point that I often revert to string concatenation —generally a sign that there is a more elegant solution lurking. 这种方法有效,但是看起来很尴尬,就像您在Perl中看到的那样,以至于我经常恢复为字符串连接-通常表明存在着更优雅的解决方案。 Is there one? 有一个吗?

The templating can be turned off using the tags <%text> and </%text> ( ref ). 可以使用标签<%text></%text>ref )关闭模板。 Anything in between will be rendered as text and not parsed. 两者之间的任何内容都将呈现为文本,并且不会解析。

<script>
//This is just an example
let entry = {title: '${some_py_value}'} //Mako templating
<%text>
$('body').append(`${entry.title}`); //JS templating
</%text>
</script>

This has the advantage over ${'${jsVariable}'} if the two are not intermixed, ie one is passing the Python variables in JS first all at once, which is what should be happening*. 如果两者没有混合使用,则具有优于${'${jsVariable}'}的优势, ,这是一次同时在JS中传递Python变量,这应该发生*。 The catch is %if and %for will not work in %text blocks, but those ought to JS encoded. 要注意的是%if%for不能在%text块中工作,但是应该使用JS编码。

∗) Okay, ideally, the HTML page served should be generic without with the main JS code externally as a single file with the user data filled by several ajax requests. ∗)好的,理想情况下,所提供的HTML页面应该是通用的,而外部的主要JS代码不应作为单个文件包含在外部,而用户数据由多个ajax请求填充。 Although there are always corner-cases ( eg Huge Python non-JSON serialisable objects with a complicated and computationally heavy method that needs to be frequently called but cannot be run as series of ajax request as the data needs to initialized first but cannot be stored serverside etc.). 尽管总是存在极端情况( 例如 ,具有复杂且计算量大的方法的庞大的Python非JSON可序列化对象,需要经常调用该方法,但由于需要首先初始化数据但不能在服务器端进行存储,因此无法作为一系列Ajax请求运行)等等。)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM