开发者

How to check if all values for liquid template are provided?

I have liquid templates stored in DB and before rendering, I would like to check, if all params required by the tem开发者_C百科plate are provided - by now I found something like:

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

and then before rendering I have a function

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

Is there a cleaner way to achieve this validation?

Thanks for all suggestions, Santuxus


I just did something similar and use a custom validator against my template body when I create the template, eg

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

then I have a EmailTemplateValidator which validates fields against the template type eg

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    

end

the plan then is to add new case blocks to the validator as new templates are required in the app with the tokens that they must contain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜