Ruby/Jekyll插件问题:如何在插件中渲染Liquid变量
Fixing Liquid Variable Rendering in Jekyll Shell Command Plugin
我明白你遇到的问题了——当你用{% shellcmd image-responsive "{{ include.asset }}" %}调用自定义插件时,{{ include.asset }}这个Liquid变量没有被正确渲染成实际值,导致shell命令没法拿到预期的参数。咱们来一步步解决这个问题:
问题根源
你原来的代码里,render_variable方法需要接收Jekyll的上下文(context)来解析Liquid变量,但在render方法中调用它时,错误地传入了@text而不是当前的context。这就导致Liquid模板无法访问include.asset这类上下文变量,自然解析不了占位符。
修正后的插件代码
我们可以简化代码逻辑,直接在render方法里完成变量渲染和命令执行:
module Jekyll class ShellCommand < Liquid::Tag def initialize(tag_name, text, tokens) super # 移除文本前后的空白,避免多余空格干扰shell命令 @text = text.strip end def render(context) # 利用当前上下文渲染Liquid变量,替换{{ include.asset }}为实际值 rendered_command = Liquid::Template.parse(@text).render(context) # 执行shell命令并返回去除首尾空白的结果 `#{rendered_command}`.strip end end end Liquid::Template.register_tag('shellcmd', Jekyll::ShellCommand)
额外的安全优化(可选但推荐)
如果你的命令参数可能包含空格、引号或其他特殊字符,直接拼接命令字符串会有shell注入风险,也可能导致命令执行失败。可以借助Ruby的Shellwords库来转义特殊字符:
require 'shellwords' module Jekyll class ShellCommand < Liquid::Tag def initialize(tag_name, text, tokens) super @text = text.strip end def render(context) rendered_command = Liquid::Template.parse(@text).render(context) # 转义命令中的特殊字符,避免解析错误和安全问题 escaped_command = Shellwords.escape(rendered_command) `#{escaped_command}`.strip end end end Liquid::Template.register_tag('shellcmd', Jekyll::ShellCommand)
测试验证
修改后,当你调用{% shellcmd image-responsive "{{ include.asset }}" %}时,Liquid会先把{{ include.asset }}替换成对应的实际值,再把完整的命令传给shell执行,就能得到你预期的结果了。
内容的提问来源于stack exchange,提问作者alexandre1985
相关产品推荐
相关产品推荐

