0

I have two content types :

  • Content type 1 named book with two fields author and language

  • Content type 2 named movie with two fields date and resolution

In my-theme/templates/page.html.twig I want to render a first section with all the books and a second section with all the movies :

<div id="first-section">

<h3>Book Author 1</h3>
<p>Book Language 1</p>

<h3>Book Author 2</h3>
<p>Book Language 2</p>

<h3>Book Author 3</h3>
<p>Book Language 3</p>

</div> 


<div id="second-section">

<h3>Movie Date 1</h3>
<p>Movie Resolution 1</p>

<h3>Movie Date 2</h3>
<p>Movie Resolution 2</p>

<h3>Movie Date 3</h3>
<p>Movie Resolution 3</p>

</div> 

How can I achieve that in Drupal 8 and Twig, is it mandatory to use pre-processing and provide the template with the variable, should I create views or blocks and render them in my page... What is the correct way to do that?

A concrete example will be much appreciated !

<div id="first-section">
    {% for book in books %}
            <h3>{{ [Book Author Here] }}</h3>
            <p>{{ [Book Language Here] }}</p>
    {% endfor %}
</div>

<div id="second-section">
    {% for movie in movies %}
            <h3>{{ [Movie Date Here] }}</h3>
            <p>{{ [Movie Resolution Here] }}</p>
    {% endfor %}
</div>
1

These types of problems are usually solved using Views.

You can create a single Page Display in Views listing the two Content Type nodes. Set the Page Path to what your link to that page to be. Add Sort Criteria by Content type so all the book nodes appear before the movie nodes (add more Sort criteria if necessary after that one). Make sure you set the Fields to be Hidden if Empty, since the two CTs you want to list don't share any Fields. Set that under each Field settings, and under Format settings.

Another, probably more common way to build the lists is to create two different Views Displays, one for each Content Type. For example you can create a Page Display to list only the book nodes with the two related Fields, then add Attachment Display in the same View and override it to show only movie nodes. Also override the Fields to show the two Fields you have on movie CT, instead of the two Fields from the book CT. Set the Attachment to show on the Page Display.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.