Can the Liquid Ruby template engine deal with Rail

2019-05-13 16:07发布

I've been searching for a template engine to allow users to create lessons and exercises online easily.

Seems like Liquid is the most popular for use in Rails. Can Liquid users easily create rails forms?

Normally I create forms in ERB with:

<%= form_for(@lesson) do |f| %>
  <% if @lesson.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@lesson.errors.count, "error") %> prohibited this lesson from being saved:</h2>

      <ul>
      <% @lesson.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div>lots of fields</div>
<% end %>

Rails will automatically insert the CSRF protection stuff among other things. Can I do the same with Liquid? Can I create filters, tags and/or blocks in Liquid to emulate Rails form tags?

1条回答
爷、活的狠高调
2楼-- · 2019-05-13 16:53

You can register your own tag blocks with Liquid, but it doesn't came out of the box.

If you check the documentation, you will notice that you can create your own tag blocks.

You can register your own tag block

class LiquidForm < Liquid::Block
  def initialize(tag_name, markup, tokens)
     super
  end

  def render(context)
    form_tag("/hello_word") do 
      input_tag "hello"
    end
  end
end

Liquid::Template.register_tag('liquid_form', LiquidForm)

And then parse the text you want with liquid

text = " {% liquid_form %} Form content {% endliquid_form %} "
@template = Liquid::Template.parse(text)
查看更多
登录 后发表回答