codeandcloud
codeandcloud

Reputation: 55308

pass multiple content from layout to page

I would like to know if there is a way to pass a dynamic named content to the page from the layout.

For example,

Layout

<body>
    <div class="container">
        {{ content }}
    </div>
    <footer>
        <p>&copy; Company 2015</p>
    </footer>
    <script src="path/to/jquery.js"></script>
    {{ page.other_content }}<!-- Objective: To write scripts that varies with page -->
</body>

Page

--- 
layout: default
title: About Us Page
---

<p> This is about us page </p>

{% capture other_content %}
<script>
    $(document).ready(function(){
        console.log("About us page.");
    });
</script>
{% endcapture %}

Is there a way to render multiple content sections in pages from layout?


In ASP.NET we can do this is the Layout page.

@RenderSection("scripts", required: false)

In content page we can render that section like this.

@section scripts {
    Hey I'm actually on the _Main layout. 
    I can vary according to the page.
    My presence is not mandatory in every page
}

Can this be done with jekyll?

Upvotes: 4

Views: 1406

Answers (1)

approxiblue
approxiblue

Reputation: 7122

GitHub Pages disallow plugins, so I'll stick to vanilla Jekyll workarounds. You can of course use plugins, generate your site locally and host the results on GitHub.


This is ugly, but possible. Keep your layout as is:

<body>
  <!-- varies with page -->
  {{ page.other_content }}
</body>

Then in your page file, define the property other_content in the front matter:

---
other_content: |
  <script>
    console.log("You can't stop me!");
  </script>
---

The pipe character denotes a multiline string. Per YAML's rules, your scripts must be indented by spaces (no tabs allowed).


If your scripts become too large, you can move them to separate files, and the front matter of your pages would refer to the script file names instead:

---
scripts: [test]
---

In the layout:

{% for s in page.scripts %}
<script src="{{ s }}.js"></script>
{% endfor %}

This works if test.js is in the same directory as the page using it. You can use site.baseurl to get absolute paths, etc.

Upvotes: 7

Related Questions