Injecting Dynamic Content into a Layout

Last edit: Feb 28, 2020

This guide will help you inject dynamic content from a page into a layout using the content_for and yield tags. This is often used when setting metadata for a particular page (i.e. title tag contents), loading per-page javascript, or per-page stylesheet.


To follow the steps in this tutorial, you should have created a page and a layout.


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

Step 1: Use yield in layout

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

<!doctype html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{% yield 'meta_title' %}</title>

    {{ content_for_layout }}

Step 2: Use content_for in page

Add the content_for tag in the previously created home.liquid page. The positioning of this line doesn't matter as long as it's in the content part of the page.

{% content_for 'meta_title' %}Homepage title{% endcontent_for %}

Sync or deploy. You can now see that the Homepage title is displayed in your browser's title bar or tab.

Add content_for to all pages in the same way, and the page title will be dynamically displayed 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.


We are always happy to help with any questions you may have.