Injecting Dynamic Content into a Layout

Last updated on June 26, 2024.

This document discusses how you could inject dynamic content from a page into a layout using the and tags. This method is often used when setting the metadata for a particular page (i.e. title tag contents), loading per-page javascript, or per-page stylesheet.

Prerequisites

To follow the steps in this tutorial, first creat a page and a layout:

Steps

Injecting dynamic content into a layout is a two-step process:

  • Step 1: Use 'yield' in a layout
  • Step 2: Use 'content_for' on a page

Step 1: Use 'yield' in a layout

Add the tag to the previously created layout file, e.g. switch the layout title to dynamic content with the tag:

app/views/layouts/application.liquid

Step 2: Use 'content_for' on a page

Add the tag to the previously created page. The line's position doesn't matter as long as it's in the content part of the page.

app/views/pages/index.liquid

Sync or deploy. The Homepage title is now displayed in your browser's title bar or tab.

Add to all pages in the same way, and the system will dynamically display the page title for each page.

Next Steps

Congratulations! You have injected dynamic content into a layout. Now you can learn how to reuse code across multiple pages using partials: Reusing Code Across Multiple Pages

Have a suggestion for this page?

Didn't quite find what you are looking for or have feedback on how we can make the content better then we would love to hear from you. Please provide us feedback and we will get back to you shortly.