问题相当复杂。假设我的函数的输入是一个字符串。输入可以包含以下关键字:
"{% if some_condition %}"(开始)"{% endif %}"(结尾)"{% else if some_other_condition %}"(选修的)"{% else %}"(选修的)
除了这些关键字,输入还可能包含任何其他字符串。条件基本上只是变量的名称,因此在解析之前的字符串中,它们只是字符串(任何有效的字符串都可以作为变量名)。
以下是该函数的用途:
- 获取输入并查找开始和结束标记对。
- 找到后,查看开始标签和结束标签之间的内容。
- 如果内容包含
"{% else if <any_condition> %}"OR"{% else %}",则什么也不做。 - 否则,将
"{% else %}<div class='empty'>Empty</div>"字符串添加到内容的末尾。
因此,为清楚起见,这是一个示例输入:
{% if username %}
<p>Hello {{ username }}</p>
{% endif %}
{% if score > 10 %}
<p>You are doing great.</p>
{% else if score > 50 %}
<p>You are freaking amazing!</p>
{% endif %}
<p>This is your <strong>awesome</strong> profile page.</p>
{% if not email %}
<p>Please consider setting your email address</p>
{% endif %}
{% if balance > 0 %}
<p>You are ready to go!</p>
{% else %}
<p>No balance</p>
{% endif %}
输出如下:
{% if username %}
<p>Hello {{ username }}</p>
{% else %}<div class="empty">Empty</div>{% endif %}
{% if score > 10 %}
<p>You are doing great.</p>
{% else if score > 50 %}
<p>You are freaking amazing!</p>
{% endif %}
<p>This is your <strong>awesome</strong> profile page.</p>
{% if not email %}
<p>Please consider setting your email address</p>
{% else %}<div class="empty">Empty</div>{% endif %}
{% if balance > 0 %}
<p>You are ready to go!</p>
{% else %}
<p>No balance</p>
{% endif %}
简而言之,如果if块内的内容没有条件,那么额外的字符串将附加在结束标记之前。希望这是有道理的。我知道有很多要求,但是有人可以让我朝着正确的方向开始吗?我不太擅长使用 JavaScript 的正则表达式,它基本上是在踢我的屁股。谢谢你的帮助!