Now you have a basic grasp on the Liquid template engine itself, let’s learn how to utilize it in our Ruby on Rails application. First you need to add the gem to the Gemfile. Add the following line to the Gemfile:
1
|
|
Then run bundle install
to install the Liquid gem:
1
|
|
Then create a model called Page. The Page model will be used to represent a page owned by a specific user. Run the commands below to create this model:
1 2 |
|
Then open up your seeds (db/seeds.rb
) file and modify it so that it looks somethings like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
Then run rake db:seed
command to seed the database with your sample data:
1
|
|
Then create a homes controller that will allow you to play with liquid. Run the command below to create the homes controller:
1
|
|
Then create a pages controller. This controller will be used to display a user’s page. Run the commands below to create the pages controller:
1
|
|
Then modify your routes (config/routes.rb
) file so that it looks somethings like below:
1 2 3 |
|
Then modify your homes controller (app/controllers/homes_controller.rb
) to pull down a list of all the user’s pages. Open up your homes controller and modify it so that it looks somethings like below:
1 2 3 4 5 |
|
Then modify your pages controller (app/controllers/pages_controller.rb
) to pull down the correct page for the specified user. Open up your pages controller and modify it so that it looks somethings like below:
1 2 3 4 5 |
|
Then create a few helper (app/helpers/pages_helper.rb
) methods for use with this example. Open up your pages helper and modify it so that it looks somethings like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
The codes above gives you some sample data to play around with.
Then modify your pages show view (pp/views/pages/show.html.erb
) to look somethings like below:
1 2 3 4 5 |
|
The codes above tells Rails to render your template using the Liquid Template Engine.
Finally, open up the show view for your home controller (app/views/homes/show.html.erb
) and add in the code listed below:
1 2 3 4 5 6 |
|
If you fire up a rails server and visit your development site, you’ll notice that you can browse each user’s pages and get a customized version of each one.
However, what if you want to use the Liquid templating engine as a replacement for erb itself? take it easy, first, create a new file in the lib folder called liquid_view.rb (lib/liquid_view.rb
) and add in the codes listed below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
Create an initializer called liquid_template_handler (config/initializers/liquid_template_handler.rb
) and add the code listed below:
1 2 |
|
Let restarting your Rails server you will be able to create actual views with the .liquid extension that uses the liquid templating engine.
So far so good, That’s it! See ya! :)