Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I dynamically load variables in Liquid templates?

Yi Mei Wang asked in General

I'm new to using Liquid templates, but I'm wondering how do I load data dynamically in my controller? The reason is because all the data is stored in my db in different tables, and loading all of them requires a lot of join queries and more of than not, a single page will almost never use all of the queried data.

I don't think it's efficient to run 20+ queries to only use 5, is there a way to know what the Liquid needs and only load those when necessary?

Reply

Yup! For standard use you can just pass it the content from a record that has handlebars in it, and call render with a parameters hash.

<%= Liquid::Template.parse(@blog.custom_content).
      render('page_content' => Post.first.content, 'page_title' => Post.first.title) %>
Reply

Using your example, I'm thinking more of only querying Page.first.content if the template itself uses page_content. I'm in a situation where my liquid templates are user generated, so I'm not sure what data will be required.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.