New Discussion

Notifications

You’re not receiving notifications from this thread.

How do I dynamically load variables in Liquid templates?

2
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?

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) %>

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.

Join the discussion
Create an account Log in

Learning Ruby on Rails? Join our newsletter.

We won't send you spam. Unsubscribe at any time.