I have liquid templates stored in DB and before rendering, I would like to check, if all params required by the template 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With