【问题标题】:How to check if all values for liquid template are provided?如何检查是否提供了液体模板的所有值?
【发布时间】:2011-05-03 14:02:15
【问题描述】:

我在数据库中存储了液体模板,在渲染之前,我想检查一下,是否提供了模板所需的所有参数 - 现在我发现了类似的东西:

parsed = Liquid::Template.parse(string_with_template)
required = parsed.instance_values["root"].instance_values["nodelist"].select{ |v| v.is_a?(Liquid::Variable) }.map(&:name)

然后在渲染之前我有一个函数

def has_all_required?(liquid_params, required)
  keys = liquid_params.keys
  required.each{|e| return false unless keys.include?(e) }
  return true
end

是否有更简洁的方法来实现此验证?

感谢所有建议, 山神

【问题讨论】:

    标签: ruby-on-rails liquid


    【解决方案1】:

    我刚刚做了类似的事情,并在创建模板时对我的模板主体使用了自定义验证器,例如

    validates :body, :presence => true, :email_template => true
    

    然后我有一个 EmailTemplateValidator,它根据模板类型验证字段,例如

    def validate_each(object, attribute, value)
        case object.template_type
        when 'registration'
            # registration_welcome emails MUST include the activation_url token
            if !value.include?('{{activation_url}}')
                object.errors[attribute] << 'Registration emails must include the {{activation_url}} token'
            end
        end    
    

    结束

    然后计划将新案例块添加到验证器,因为应用程序中需要新模板以及它们必须包含的令牌。

    【讨论】:

    • 问题是模板可以在管理面板中编辑,所以我需要一个通用的方法——如果我知道所有必需的值,我可以使用你的方法,谢谢你的回答;)我的意思是例如:page_title 可以具有值:'This is {{product_name}}',然后更改为'This is {{product_name}} of a price {{product_price}}'。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2016-07-05
    • 2020-10-09
    • 2016-06-18
    相关资源
    最近更新 更多