gpt4 book ai didi

javascript - 如何为类似液体的模板语言编写简单的 peg 语法?

转载 作者:行者123 更新时间:2023-11-29 22:58:36 26 4
gpt4 key购买 nike

编辑:您可以在此处关注进度:https://github.com/simple-updates/template

我正在使用 peg.js并尝试编写一些可以解释模板的东西,例如:

hello {{ "world" }}
{% if a %}
good {{ a }}
{% else %}
bad
{% endif %}

我已经尝试了很多东西,但假设这是我的起点:

Template
= ws markup ws

ws = " "*

open_interpolation = "{{"
close_interpolation = "}}"
open_tag = "{%"
close_tag = "%}"

char = . // ?

markup =
(open_tag tag:char* close_tag)
{ return { 'tag': tag.join('') } } /
(open_interpolation interpolation:char* close_interpolation)
{ return { 'interpolation': interpolation.join('') } } /
chars:char*
{ return { 'chars': chars.join('') } }

例如,当我尝试字符串 {{ test }} 时,它只会将其解释为字符而不是插值。

知道我该怎么做吗?

(显然嵌套“标记”会更复杂)

最佳答案

像这样的事情作为开始怎么样:

Template
= Atom*

Atom
= IfTag
/ Interpolation
/ [^{]
/ !"{%" !"{{" "{"

Interpolation
= "{{" _ Expression _ "}}"

IfTag
= If Template ( Else Template )? EndIf

If
= "{%" _ "if" _ Expression _ "%}"

Else
= "{%" _ "else" _ "%}"

EndIf
= "{%" _ "endif" _ "%}"

Expression
= "\"" [^"]* "\""
/ [a-zA-Z]+
/ [0-9]+

_
= [ \t\n\r]*

这里棘手的部分是 !"{%"!"{{""{" Atom 生产的替代方案,其内容如下:

When no "{%" and "{{" can be seen ahead of the current position, match a single "{"

关于javascript - 如何为类似液体的模板语言编写简单的 peg 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com