curly_brackets
curly_brackets

Reputation: 5598

Timber/Twig define Block

I'm new to Timber/Twig, but so far I'm loving it!

I would like to have a folder with partials/components or "blocks" as Timber/Twig calls them, so I could have say a "video.twig" component, that can be reused through out the page.

1) How can I "register" the components/block in a folder?

2) How can I "feed" the component/block with data? I would like to do something like this:

{% block component DATA %}

Upvotes: 0

Views: 347

Answers (2)

Sonia Verma
Sonia Verma

Reputation: 77

  1. Timber doesn’t require you to "register" components explicitly like some frameworks do. Instead, you just need to organize your .twig files inside a folder (e.g., views/components/) and reference them in your templates.
/wp-content/themes/your-theme
  ├── views/
  │   ├── components/
  │   │   ├── video.twig
  │   │   ├── button.twig
  │   │   ├── card.twig
  │   ├── page.twig
  │   ├── single.twig
  ├── functions.php
  ├── index.php
  1. Example of a video.twig Component:
<div class="video-wrapper">
    <video controls>
        <source src="{{ video_url }}" type="video/mp4">
        Your browser does not support the video tag.
    </video>
    {% if caption %}
        <p class="video-caption">{{ caption }}</p>
    {% endif %}
</div>
  1. Now, in your page.twig or any other template file:
{% include 'components/video.twig' with { video_url: 'https://example.com/video.mp4', caption: 'My awesome video' } %}

That way you can easily make compinents and reuse in any file using include function. This is very useful for writing maintainable and cleaner code.

Upvotes: 0

mp31415
mp31415

Reputation: 6689

The syntax in include looks like this:

{% include "comment.twig" with {comment:cmt} %}

It may work for the block too. Give it a shot.

Upvotes: 1

Related Questions