【发布时间】:2021-02-04 11:29:13
【问题描述】:
我有时需要生成文本文件。到目前为止的案例是纯文本电子邮件和配置文件。在前一种情况下,你必须精确,你不能逃避,“你知道,那些是生成的,即使这里和那里有额外的空格,它们仍然是可读的。”在后者你可以,但有一个可读的结果是很好的。
现在,我如何使结果精确(就空格而言),并且模板也可读?比后面的更易读。
有了jinja,我可以做到这一点:
{%- if order.name -%}
Name: {{ order.name + '\n' -}}
{%- endif -%}
Phone: {{ order.phone + '\n' -}}
{%- if order.branch or order.address -%}
{{- '\n' -}}
{%- if order.branch -%}
Branch: {{ order.branch + '\n' -}}
{%- endif -%}
{%- if order.address -%}
Address: {{ order.address + '\n' -}}
{%- endif -%}
{%- endif -%}
{%- for pvxo in order.productvariantxorders.all() -%}
{{- '\n' -}}
Product: {{ (pvxo.productvariant.product.name
if pvxo.productvariant
else pvxo.product.name) + '\n' -}}
{%- endfor -%}
可能会产生:
Name: ...
Phone: ...
Address: ...
Product: ...
Product: ...
但我花了一段时间才弄清楚如何让jinja 表现得这样。
使用 Javascript (_.template):
const _ = require('lodash');
const tpl =
'<% if (order.name) { %>'
+ 'Name: <%= order.name %>\n'
+ '<% } %>'
+ 'Phone: <%= order.phone %>\n'
+ '<% if (order.branch || order.address) { %>'
+ '\n'
+ '<% if (order.branch) { %>'
+ 'Branch: <%= order.branch %>\n'
+ '<% } %>'
+ '<% if (order.address) { %>'
+ 'Address: <%= order.address %>\n'
+ '<% } %>'
+ '<% } %>'
+ '<% order.productvariantxorders.forEach(pvxo => { %>'
+ '\n'
+ 'Product: <%= pvxo.productvariant'
+ ' ? pvxo.productvariant.product.name'
+ ' : pvxo.product.name %>\n'
+ '<% }) %>';
console.log(_.template(tpl)({
order: {
name: '...',
phone: '...',
address: '...',
productvariantxorders: [
{productvariant: {product: {name: '...'}}},
{product: {name: '...'}},
],
}
}));
哪个更直接。
而且这 2 个不包括您需要缩进的情况。这些仍然是我能想到的最好的解决方案。似乎没有很多选择。这个问题与语言无关。您可以指向一些提供更好结果的特定模板引擎。或者只是建议这种语法的想法。
顺便说一句,这是我检查了答案的somewhat related question。
【问题讨论】:
-
经过一些编辑,这个问题可能是 Software Recommendations Stack Exchange 的主题。
-
@oguz ismail 现在我需要它专门用于 shell 脚本。
-
@ToddA.Jacobs 我已经编辑了这个问题,并相信这样它不再是关于建议。它寻求一种方法。
标签: template-engine