This is a very simplified starting point for using Liquid templates that are stored in a MongoDB collection. Includes some
nice features such as auto-inclusion of all custom LiquidDrops in all templates, auto-inclusion of the current_user in all
templates, and auto-inclusion of all instance variables defined in the controller method rendering the view.
Note that with MongoMapper::Document objects, it seems that using the liquid_methods :foo, :bar way of creating on-demand
LiquidDrops doesn’t work properly with the plugin. I haven’t bothered to fix this, since I think that’s a lame way of doing it
in the first place.
So you should do this instead in your models for any data you want available in a Liquid template:
def to_liquid
{'name' => name, 'biography' => biography, 'created_at' => created_at}
end
Note that you must use string-based keys, not symbols!
… or, you can create custom LiquidDrops.
Just install it as a plugin into your Rails project and make sure you have MongoDB and MongoMapper:
./script/plugin install git://github.com/mepatterson/mongo_liquid_templates.git
You need to install various gems, if you don’t already have them:
gem install liquid
gem install mongo
gem install mongo_ext
gem install mongomapper
Probably need to require these gems in your config/environment.rb file:
config.gem "liquid"
config.gem "mongo"
config.gem "mongo_ext"
config.gem "mongomapper"
Add a template to the Mongo collection:
DynamicTemplate.create(:path => "person", :body => "<h2>{{ person.name }}</h2>\n<p>{{ person.biography }}</p>")
- All normal controller instance variables such as @post or @comments will be available as ‘post’ or ‘comments’ from inside the Liquid template. Your usual Rails helpers are also available as Liquid filters.
- If you’ve defined a current_user method, that will be automagically passed into any template or nested template.
- Any LiquidDrops defined in app/liquid_drops will be available to ALL templates and nested templates.
Do this to render a liquid template from the database (example in HAML):
= render_liquid('person')
I borrowed a big chunk of code from akitaonrails/dynamic_liquid_templates , so this plugin can do all the same stuff in terms
of passing different namespaces, collections, etc. Look at the docs for that plugin to see how this works.
http://github.com/akitaonrails/dynamic_liquid_templates
M. E. Patterson (madraziel@gmail.com) – http://blog.digimonkey.com