ether/atom

Adding enhanced modularity to Craft CMS Twig templating

Installs: 1 232

Dependents: 0

Suggesters: 0

Security: 0

Stars: 9

Watchers: 5

Forks: 2

Open Issues: 1

Type:craft-plugin

5.0.0 2024-03-27 15:19 UTC

This package is auto-updated.

Last update: 2024-11-28 19:05:16 UTC


README

Adding enhanced modularity to Craft CMS Twig templating

Atom

Installation

$ composer require ether/atom

Usage

Create a folder called _atoms in your templates directory (this can be customised, see Config).

Basic

In this folder you can create re-usable twig templates, or atoms (a.k.a. modules, components, molecules). You can access the atoms in twig using the following syntax:

{% x:my-atom %}

The above will include _atoms/my-atom in your template. If my-atom doesn't exist then nothing will be output.

Parameters

You can pass parameters to your atom which will be exposed within the atom. The current template context is NOT passed to the atom, so any variables defined outside will have to be passed manually.

{% x:my-atom { heading: "Hello world!" } %}

In the above example, my-atom will be given access to the heading variable. If heading isn't passed then the variable will be undefined. You'll want to check variable availability with is defined or |default.

Children

Children can also be passed to atoms:

{% x:my-atom { heading: "Hello world!" } %}
    <p>This is my atom</p>
    <p>There are many like it, but this is mine</p>
    <p>{{ myVariable }}</p>
{% endx:my-atom %}

Children are rendered in the parent context, not the atoms. This means any variables you pass to the atom will not be available in the children (unless they are also available in the parent context).

Children are rendered within the atom using the children variable, which will contain the rendered contents of the children or null if no children are defined.

{# Contents of `_atoms/my-atom` #}
<div>
    <h1>{{ heading }}</h1>
    {{ children }}
</div>

Nested

Atoms can be nested inside other atoms!

{% x:my-atom %}
    {% x:another-atom %}
{% endx:my-atom %}

Sub-folders

You can store atoms in folders within your _atoms directory. For example, if you had an atom at _atoms/cards/news, you could access it using the following syntax:

{% x:cards/news %}

Dynamic Atoms

You can render atoms with dynamic names by wrapping the atom name in square brackets:

{% set myVar = 'example-atom' %}

{% x:[myVar] %}

{% x:[myVar] %}
    <p>hello world!</p>
{% endx:[myVar] %}

Config

You can configure Atom by creating a atom.php file in your config folder. See config.php for the available settings.