ruby-on-rails 如何从Liquid模板中删除所有标签?

bprjcwpo  于 7个月前  发布在  Ruby
关注(0)|答案(2)|浏览(62)

我有这个Liquid模板:

Hello, {% foo %} world!

字符串
我想从这里删除foo标签和所有其他标签,以获得一个干净的文档,没有任何Liquid标记:

Hello, world!


是否可以通过使用现有的Liquid工具来实现这一点?

v9tzhpje

v9tzhpje1#

使用Python Liquid中的lexer,可以抓取文本模板文本标记,然后将标记值重新连接在一起。这将删除输出表达式({{ ... }})和标记。

from liquid.lex import get_lexer
from liquid.token import TOKEN_LITERAL

tokenize = get_lexer()
template = "Hello, {% foo %} world!"
tokens = tokenize(template)  # an iterator
template_text = "".join(t.value for t in tokens if t.type == TOKEN_LITERAL)

print(template_text) # Hello,  world!

字符串
免责声明:我是Python Liquid的作者。

bgibtngc

bgibtngc2#

Python正则表达式解决方案示例

Liquid本身并没有提供一个工具或专门可以做到这一点的东西,但它很容易解决。
使用PythonRegex,您可以编写执行您想要的操作的逻辑。

正则表达式在Python中的用法示例:

import re

def remove_liquid_tags(text):
    # This Regex pattern matches for both {{ }} and {% %} fine
    pattern = r'\{\{.*?\}\}|\{\%.*?\%\}'
    return re.sub(pattern, '', text)

liquid_template = "Hello, {% foo %} world!"
clean_document = remove_liquid_tags(liquid_template)

# The Final Print
print(clean_document)

字符串
输出将为Hello, World,根据您的需要调整Regex

相关问题