Components
Components are pieces of template code that can be included in other templates. They are useful for reducing duplicate code in your templates. To add a new component, go to the design editor screen and you'll see add button for new component.
Components are most commonly used to generate HTML document's HEAD-section, site navigation menu or site header and footer.
Components have access to the same variables and objects that are available in the template that includes the component.
Example
Create a component named "Header" with the following content
<h1>My site header</h1>
And let's include it from page template
<!DOCTYPE html>
<html>
<body>
{% include "Header" %}
</body>
</html>
The resulting output is
<!DOCTYPE html>
<html>
<body>
<h1>My site header</h1>
</body>
</html>
Variable scoping
As stated above, component has access to all variables and objects that are in scope of template. Let's look at more interesting example where outer template loops through the list of latest articles on site and component renders header and excerpt for article:
<!DOCTYPE html>
<html>
<body>
{% for article in site.latest_articles %}
{% include "Article" %}
{% endfor %}
</body>
</html>
Let the component named "Article" contain the following:
<h2>{{ article.title }}</h2>
<p>{{ article.excerpt }}</p>
Rendering the template will result something like this:
<!DOCTYPE html>
<html>
<body>
<h2>First article</h2>
<p>Excerpt for first article</p>
<h2>Second article</h2>
<p>Excerpt for the second article</p>
</body>
</html>
Extra variables
When including components, it is sometimes useful to provide extra variables that are available to only that component.{% include "component" foo: "bar" %}
The above example shows how the component named "component" is included with an extra variable. Inside the component, using {{ foo }}
will yield bar
.