Answers.Body: <p>I'm not sure I understand your question 100%, but I'm assuming you're talking about a thoroughly modular approach to templating, and not about letting your end users/content editors actually edit the <em>content model</em> (i.e. create/edit Sections, fields, field layouts etc) – because the latter is <strong>not</strong> a good approach, in general.</p>
  
  <p>Either way, this is a very open question, so this answer is kind of broad (or in any case, it just outlines one way to do it, focused on entries and fields).</p>
  
  <p>Note that I haven't seen the Mijingo videos, but I think the answer to your use case is probably to go with a partial-heavy approach. <em>Basically, a "partial" is an incomplete/modular template that you can include in another template.</em></p>
  
  <p>First off, you might want to create a "catch-all" template (let's just assume your catch-all template is called <code>templates/index.html</code>). Be sure to add the path to that template (which would just be <code>index</code>) to the <em>Entry Template</em> setting for all relevant Sections, to make sure the same, catch-all template is always loaded for all entry URLs.</p>
  
  <p>Then, assuming your site has three fields – <code>heading</code>, <code>image</code> and <code>body</code> – you'd create <em>a partial template for each of these fields</em>. It's a good idea to store your partials in a folder prefixed with an underscore, to make sure Craft doesn't include them whenever it maps URL routes to template paths (these templates aren't standalone and should never be rendered on their own). So for the three fields in our example, you'd create these three templates:</p>
  
  <p><code>/templates/_partials/heading.html</code><br>
  <code>/templates/_partials/image.html</code><br>
  <code>/templates/_partials/body.html</code></p>
  
  <p>Here's how the <code>heading.html</code> partial could look:</p>
  
  <p><code>{% if element.heading %}
      &lt;h1 class="heading"&gt;{{ element.heading }}&lt;/h1&gt;
  {% endif %}
  </code></p>
  
  <p>Inside your catch-all template, you'd then need to <a href="http://twig.sensiolabs.org/doc/tags/include.html" rel="noreferrer"><code>{% include %}</code></a> these partial templates, following some logic of your choice.</p>
  
  <p>Here's an approach that basically loops through all fields for the current <code>entry</code>'s field layout, attempting to include a partial template for each field:</p>
  
  <pre><code>{% extends '_layout' %}{# Assuming this template extends a basic layout template #}
  {% block content %}
  
      {# Get all fields, indexed by field ID #}
      {% set allFields = craft.fields.getAllFields('id') %}
  
      {# Get the IDs for all fields in this entry's field layout #}
      {% set fieldIds = entry.getFieldLayout().getFieldIds() %}
  
      {# Loop through the entry fields' IDs; attempt to include template based on each field's handle #}
      {% for fieldId in fieldIds %}
          {% set field = allFields[fieldId] ?? null %}
          {% if field and entry[field.handle] %}
              {% include '_partials/'~field.handle ignore missing with { element: entry } %}
          {% endif %}
      {% endfor %}
  
  {% endblock %}
  </code></pre>
  
  <p>A couple of things to note:</p>
  
  <p>First, the above code builds the template path to each partial dynamically, by joining the root path (<code>'_partials/'</code>) with each field's <code>handle</code> property (using the tilde operator <code>~</code>). In other words, this solution hinges upon using the fields' handles for the partial templates' filenames. Note that its also possible to pass an array of template paths to the <code>{% include %}</code> tag, in which case Craft will attempt to load the next template in that array whenever it fails the load the former. Here's how that could look:</p>
  
  <pre><code>{% include ['_partials/matrix/'~field.handle, '_partials/fields/'~field.handle] ignore missing with { element: entry } %}`
  </code></pre>
  
  <p>With the above, Craft would first look for the template <code>/templates/_partials/matrix/title.html</code>, and if that file doesn't exist it'd look for <code>/templates/_partials/fields/title.html</code> (before failing silently due to the <code>ignore missing</code> directive).</p>
  
  <p>Second, it might seem redundant to pull <em>all fields</em> from the <a href="https://craftcms.com/classreference/services/FieldsService" rel="noreferrer">FieldsService</a>, but <a href="https://craftcms.stackexchange.com/a/2928/1098">the alternative</a> is to hit the database for every field in your entry's field layout, so this should actually be the most performant way to pull the current entry's actual <a href="https://craftcms.com/classreference/models/FieldModel" rel="noreferrer">FieldModels</a>.</p>
  
  <p>Third – the <code>with</code> statement for the <code>{% include %}</code> tag enables you to pass parameters to the included template. In this example, we're actually exposing the current entry to the included template as the more generic <code>element</code> variable. This is just future proofing in case we want to use the same partials for other element types, e.g. categories (in which case you'd use <code>with { element: category }</code>) – notice that in the example <code>heading.html</code> template above, <code>element.heading</code> is used over <code>entry.heading</code>.</p>
  
  <p>If you want to avoid variable pollution, you might pass the <code>only</code> directive aswell, in which case <em>only</em> whatever parameters passed with <code>with</code> will be made available to the included statement, nothing else:</p>
  
  <pre><code>{% include '_partials/'~field.handle with { element: entry } only %}
  </code></pre>
  
  <p>Of course, you can include other stuff in the object passed to <code>with</code>, as well. For instance, you might want to render stuff differently if the current field is either first or last in the loop:</p>
  
  <pre><code>{% include '_partials/'~field.handle with { element: entry, isFirst: loop.first, isLast: loop.last } %}
  
  {# In heading.html #}
  &lt;div class="field{{ isFirst ? ' is-first' }}{{ isLast ? ' is-last' }}"&gt;
      &lt;h2 class="heading"&gt;{{ element.heading }}&lt;/h2&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Going further; talking about Matrix fields and alluding to the fact that putting Matrix field partials in a separate templates folder might be a good idea – if you're going fully modular it might make sense to create separate templates for each Matrix block type, as well. Tons of ways to skin this cat, but one way to do it is to add a sub folder for every Matrix field, containing partials for each of the field's block types. For example, if you've got a Matrix field called <code>contentBlocks</code> with the block types <code>images</code> and <code>text</code> you might structure it like this:</p>
  
  <p><code>templates/_partials/contentBlocks.html</code> (the partial for the Matrix field itself)<br>
  <code>templates/_partials/contentBlocks/images.html</code> (the partial for the <code>images</code> block type)<br>
  <code>templates/_partials/contentBlocks/text.html</code> (the partial for the <code>text</code> block type)    </p>
  
  <p>Then, inside the <code>contentBlocks.html</code> template, you could do something like this:</p>
  
  <pre><code>{% for block in element.contentBlocks %}
      {% include '_partials/contentBlocks/'~block.type ignore missing with { block: block } only %}
  {% endfor %}
  </code></pre>
  
  <p>In fact, you might not even need the <code>contentBlocks.html</code> field template, and just do something like this in <code>index.html</code>:</p>
  
  <pre><code>{% if field.type == 'Matrix' %}
      {# Attempt to include the blocks for this Matrix field #}
      {% for block in entry.field %}
          {% include '_partials/'~field.handle~'/'~block.type ignore missing with { block: block } only %}
      {% endfor %}
  {% else %}
      {# Non-Matrix fields #}
      {% include '_partials/'~field.handle ignore missing with { element: entry } %}
  {% endif %}
  </code></pre>
  
  <p>One final thing to note – with the above solution, your entries' fields' partials will be included in the order corresponding to the entry type's field layout (i.e. the first field in the layout will be included first). This may or may not be what you want (the order that makes sense inside the CP may not always correspond to what the design/front end should look like) but if you need more control over your fields' order, you could do something like this inside <code>index.html</code>:</p>
  
  <pre><code>{% set fieldsToInclude = ['image', 'heading', 'body'] %}
  {% for fieldHandle in fieldsToInclude %}
      {% if entry['fieldHandle'] %}
          {% include '_partials/'~fieldHandle ignore missing with { element: entry ) %}
      {% endif %}
  {% endfor %}
  </code></pre>
  
  <p>The above will actually be slightly more performant than the first example, because it avoids the few database queries involved in pulling the fields dynamically.</p>
  
  <p>Of course, for optimal flexibility you'd probably go heavy on the Matrix fields, too – obviously, any Matrix block partials would render in their original order inside the Matrix fields, so with Matrix blocks your content editors will have complete control over where each piece of content actually renders.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-19T00:32:28.893Z
Answers.Text: Epic answer. A+++. Would read again.
Answers.UserDisplayName: Brad Bell
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-21T01:25:43.540Z
Answers.Text: Thank you!
  `    {# Loop through the entry fields' IDs; attempt to include template based on each field's handle #}
      {% for fieldId in fieldIds %}
          {% set field = allFields[fieldId] ?? null %}
          {% if field.type == 'Matrix' %}
              {# Attempt to include the blocks for this Matrix field #}
              {% for block in entry.field %}
                  {% include '_partials/'~field.handle~'/'~block.handle ignore missing with { block: block } only %}`
Answers.UserDisplayName: Jon Riel
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-21T01:26:45.130Z
Answers.Text: Thank you! this is what I have. but the entry field is empty, it's a {} in json output.
  ´    {# Loop through the entry fields' IDs; attempt to include template based on each field's handle #}
      {% for fieldId in fieldIds %}
          {% set field = allFields[fieldId] ?? null %}
          {% if field.type == 'Matrix' %}
              {# Attempt to include the blocks for this Matrix field #}
              {% for block in entry.field %}
                  {% include '_partials/'~field.handle~'/'~block.handle ignore missing with { block: block } only %}´
Answers.UserDisplayName: Jon Riel
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-21T01:30:49.243Z
Answers.Text: {% for block in entry.field %} entry.field does not exist in matrix. any idea why that could be?
Answers.UserDisplayName: Jon Riel
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-21T01:33:59.313Z
Answers.Text: If `field` is a variable and not an actual field handle, you'll have to use something like `{% for block in entry[field.handle] %}`.
Answers.UserDisplayName: Mats Mikkel Rummelhoff
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-21T07:22:47.467Z
Answers.Text: Thank you! I just tried this, Next exception: 'Twig_Error_Runtime' with message 'An exception has been thrown during the rendering of a template ("Neither Craft\MatrixBlockModel nor belonging Behavior have a scope "handle".") in "index" at line 36.' in /../craft/app/vendor/twig/twig/lib/Twig/Template.php:182
Answers.UserDisplayName: Jon Riel
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-21T07:54:08.200Z
Answers.Text: Sorry, that's my error. Matrix blocks don't have a `handle` attribute, i.e. it should be `block.type`, not `block.handle` in my examples above. I've amended the answer.
Answers.UserDisplayName: Mats Mikkel Rummelhoff
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-21T10:23:48.707Z
Answers.Text: Awesome, it worked all perfectly.
Answers.UserDisplayName: Jon Riel
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-12-18T22:08:37.907Z
Answers.LastActivityDate: 2016-12-21T07:54:51.817Z
Answers.LastEditDate: 2017-04-13T12:51:00.303Z
Answers.UserDisplayName: Mats Mikkel Rummelhoff
Body: <p>I am just starting out with Craft CMS.</p>
  
  <p>What I see right now is a lot of static content in the html templates. Even in the demo.</p>
  
  <pre><code>{% block content %}
  &lt;h1&gt;{{ entry.title }}&lt;/h1&gt;
  
  {{ entry.body }}
  
  &lt;h2&gt;Recent News&lt;/h2&gt;
  &lt;ul&gt;
      {% for entry in craft.entries.section('news').limit(5).find() %}
          &lt;li&gt;&lt;a href="{{ entry.url }}"&gt;{{ entry.title }}&lt;/a&gt;&lt;/li&gt;
      {% endfor %}
  &lt;/ul&gt;
  {% endblock %}
  </code></pre>
  
  <p>You see, that is very static. Is there a way to make it all more flexible and dynamic?</p>
  
  <p>I want my site to be totally flexible so that users can change the outcome completely with dragging and dropping sections in the admin area.</p>
  
  <p>I only want to define HTML for a field / section. Then, I would simply need to loop all fields through and load the html template for each section that is being used.</p>
  
  <p>This would allow massive reusability of these 'content boxes' everywhere. Basically, it'll become drag and drop website building to a large extend.</p>
  
  <p>Do you have some advice on how to do this best?</p>
  
  <hr>
  
  <p>Basically this guy is talking about it: <a href="https://mijingo.com/products/screencasts/reusable-twig-templates-craft/" rel="noreferrer">https://mijingo.com/products/screencasts/reusable-twig-templates-craft/</a></p>
  
Tags: <templating><matrix>
Title: How to: Flexible Twig Templates in Craft
ThreadText: # How to: Flexible Twig Templates in Craft
  
  (Asked by: username_0 on 2016-12-18)
  
  I am just starting out with Craft CMS.
  
  What I see right now is a lot of static content in the html templates. Even in the demo.
  
  ```
  {% block content %}
  <h1>{{ entry.title }}</h1>
  
  {{ entry.body }}
  
  <h2>Recent News</h2>
  <ul>
      {% for entry in craft.entries.section('news').limit(5).find() %}
          <li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
      {% endfor %}
  </ul>
  {% endblock %}
  
  ```
  
  You see, that is very static. Is there a way to make it all more flexible and dynamic?
  
  I want my site to be totally flexible so that users can change the outcome completely with dragging and dropping sections in the admin area.
  
  I only want to define HTML for a field / section. Then, I would simply need to loop all fields through and load the html template for each section that is being used.
  
  This would allow massive reusability of these 'content boxes' everywhere. Basically, it'll become drag and drop website building to a large extend.
  
  Do you have some advice on how to do this best?
  
  ---
  
  Basically this guy is talking about it: <https://mijingo.com/products/screencasts/reusable-twig-templates-craft/>
  
  **Tags:** templating, matrix
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2016-12-18. Score: 11
  
  I'm not sure I understand your question 100%, but I'm assuming you're talking about a thoroughly modular approach to templating, and not about letting your end users/content editors actually edit the *content model* (i.e. create/edit Sections, fields, field layouts etc) – because the latter is **not** a good approach, in general.
  
  Either way, this is a very open question, so this answer is kind of broad (or in any case, it just outlines one way to do it, focused on entries and fields).
  
  Note that I haven't seen the Mijingo videos, but I think the answer to your use case is probably to go with a partial-heavy approach. *Basically, a "partial" is an incomplete/modular template that you can include in another template.*
  
  First off, you might want to create a "catch-all" template (let's just assume your catch-all template is called `templates/index.html`). Be sure to add the path to that template (which would just be `index`) to the *Entry Template* setting for all relevant Sections, to make sure the same, catch-all template is always loaded for all entry URLs.
  
  Then, assuming your site has three fields – `heading`, `image` and `body` – you'd create *a partial template for each of these fields*. It's a good idea to store your partials in a folder prefixed with an underscore, to make sure Craft doesn't include them whenever it maps URL routes to template paths (these templates aren't standalone and should never be rendered on their own). So for the three fields in our example, you'd create these three templates:
  
  `/templates/_partials/heading.html`  
  `/templates/_partials/image.html`  
  `/templates/_partials/body.html`
  
  Here's how the `heading.html` partial could look:
  
  `{% if element.heading %}
  <h1 class="heading">{{ element.heading }}</h1>
  {% endif %}`
  
  Inside your catch-all template, you'd then need to [`{% include %}`](http://twig.sensiolabs.org/doc/tags/include.html) these partial templates, following some logic of your choice.
  
  Here's an approach that basically loops through all fields for the current `entry`'s field layout, attempting to include a partial template for each field:
  
  ```
  {% extends '_layout' %}{# Assuming this template extends a basic layout template #}
  {% block content %}
  
      {# Get all fields, indexed by field ID #}
      {% set allFields = craft.fields.getAllFields('id') %}
  
      {# Get the IDs for all fields in this entry's field layout #}
      {% set fieldIds = entry.getFieldLayout().getFieldIds() %}
  
      {# Loop through the entry fields' IDs; attempt to include template based on each field's handle #}
      {% for fieldId in fieldIds %}
          {% set field = allFields[fieldId] ?? null %}
          {% if field and entry[field.handle] %}
              {% include '_partials/'~field.handle ignore missing with { element: entry } %}
          {% endif %}
      {% endfor %}
  
  {% endblock %}
  
  ```
  
  A couple of things to note:
  
  First, the above code builds the template path to each partial dynamically, by joining the root path (`'_partials/'`) with each field's `handle` property (using the tilde operator `~`). In other words, this solution hinges upon using the fields' handles for the partial templates' filenames. Note that its also possible to pass an array of template paths to the `{% include %}` tag, in which case Craft will attempt to load the next template in that array whenever it fails the load the former. Here's how that could look:
  
  ```
  {% include ['_partials/matrix/'~field.handle, '_partials/fields/'~field.handle] ignore missing with { element: entry } %}`
  
  ```
  
  With the above, Craft would first look for the template `/templates/_partials/matrix/title.html`, and if that file doesn't exist it'd look for `/templates/_partials/fields/title.html` (before failing silently due to the `ignore missing` directive).
  
  Second, it might seem redundant to pull *all fields* from the [FieldsService](https://craftcms.com/classreference/services/FieldsService), but [the alternative](https://craftcms.stackexchange.com/a/2928/1098) is to hit the database for every field in your entry's field layout, so this should actually be the most performant way to pull the current entry's actual [FieldModels](https://craftcms.com/classreference/models/FieldModel).
  
  Third – the `with` statement for the `{% include %}` tag enables you to pass parameters to the included template. In this example, we're actually exposing the current entry to the included template as the more generic `element` variable. This is just future proofing in case we want to use the same partials for other element types, e.g. categories (in which case you'd use `with { element: category }`) – notice that in the example `heading.html` template above, `element.heading` is used over `entry.heading`.
  
  If you want to avoid variable pollution, you might pass the `only` directive aswell, in which case *only* whatever parameters passed with `with` will be made available to the included statement, nothing else:
  
  ```
  {% include '_partials/'~field.handle with { element: entry } only %}
  
  ```
  
  Of course, you can include other stuff in the object passed to `with`, as well. For instance, you might want to render stuff differently if the current field is either first or last in the loop:
  
  ```
  {% include '_partials/'~field.handle with { element: entry, isFirst: loop.first, isLast: loop.last } %}
  
  {# In heading.html #}
  <div class="field{{ isFirst ? ' is-first' }}{{ isLast ? ' is-last' }}">
      <h2 class="heading">{{ element.heading }}</h2>
  </div>
  
  ```
  
  Going further; talking about Matrix fields and alluding to the fact that putting Matrix field partials in a separate templates folder might be a good idea – if you're going fully modular it might make sense to create separate templates for each Matrix block type, as well. Tons of ways to skin this cat, but one way to do it is to add a sub folder for every Matrix field, containing partials for each of the field's block types. For example, if you've got a Matrix field called `contentBlocks` with the block types `images` and `text` you might structure it like this:
  
  `templates/_partials/contentBlocks.html` (the partial for the Matrix field itself)  
  `templates/_partials/contentBlocks/images.html` (the partial for the `images` block type)  
  `templates/_partials/contentBlocks/text.html` (the partial for the `text` block type)
  
  Then, inside the `contentBlocks.html` template, you could do something like this:
  
  ```
  {% for block in element.contentBlocks %}
      {% include '_partials/contentBlocks/'~block.type ignore missing with { block: block } only %}
  {% endfor %}
  
  ```
  
  In fact, you might not even need the `contentBlocks.html` field template, and just do something like this in `index.html`:
  
  ```
  {% if field.type == 'Matrix' %}
      {# Attempt to include the blocks for this Matrix field #}
      {% for block in entry.field %}
          {% include '_partials/'~field.handle~'/'~block.type ignore missing with { block: block } only %}
      {% endfor %}
  {% else %}
      {# Non-Matrix fields #}
      {% include '_partials/'~field.handle ignore missing with { element: entry } %}
  {% endif %}
  
  ```
  
  One final thing to note – with the above solution, your entries' fields' partials will be included in the order corresponding to the entry type's field layout (i.e. the first field in the layout will be included first). This may or may not be what you want (the order that makes sense inside the CP may not always correspond to what the design/front end should look like) but if you need more control over your fields' order, you could do something like this inside `index.html`:
  
  ```
  {% set fieldsToInclude = ['image', 'heading', 'body'] %}
  {% for fieldHandle in fieldsToInclude %}
      {% if entry['fieldHandle'] %}
          {% include '_partials/'~fieldHandle ignore missing with { element: entry ) %}
      {% endif %}
  {% endfor %}
  
  ```
  
  The above will actually be slightly more performant than the first example, because it avoids the few database queries involved in pulling the fields dynamically.
  
  Of course, for optimal flexibility you'd probably go heavy on the Matrix fields, too – obviously, any Matrix block partials would render in their original order inside the Matrix fields, so with Matrix blocks your content editors will have complete control over where each piece of content actually renders.
  
  > **Comments:**
  > **username_2**: Epic answer. A+++. Would read again.  
  > **username_0**: Thank you! `    {# Loop through the entry fields' IDs; attempt to include template based on each field's handle #}     {% for fieldId in fieldIds %}         {% set field = allFields[fieldId] ?? null %}         {% if field.type == 'Matrix' %}             {# Attempt to include the blocks for this Matrix field #}             {% for block in entry.field %}                 {% include '_partials/'~field.handle~'/'~block.handle ignore missing with { block: block } only %}`  
  > **username_0**: Thank you! this is what I have. but the entry field is empty, it's a {} in json output. ´    {# Loop through the entry fields' IDs; attempt to include template based on each field's handle #}     {% for fieldId in fieldIds %}         {% set field = allFields[fieldId] ?? null %}         {% if field.type == 'Matrix' %}             {# Attempt to include the blocks for this Matrix field #}             {% for block in entry.field %}                 {% include '_partials/'~field.handle~'/'~block.handle ignore missing with { block: block } only %}´  
  > **username_0**: {% for block in entry.field %} entry.field does not exist in matrix. any idea why that could be?  
  > **username_1**: If `field` is a variable and not an actual field handle, you'll have to use something like `{% for block in entry[field.handle] %}`.  
  > **username_0**: Thank you! I just tried this, Next exception: 'Twig_Error_Runtime' with message 'An exception has been thrown during the rendering of a template ("Neither Craft\MatrixBlockModel nor belonging Behavior have a scope "handle".") in "index" at line 36.' in /../craft/app/vendor/twig/twig/lib/Twig/Template.php:182  
  > **username_1**: Sorry, that's my error. Matrix blocks don't have a `handle` attribute, i.e. it should be `block.type`, not `block.handle` in my examples above. I've amended the answer.  
  > **username_0**: Awesome, it worked all perfectly.  
  
  ---
  
  