Should I include a view for each message? For now, I have two views using Twig:


messages.html.twig
item.html.twig


The first one is the view which displays all of the users' posts in my forum. When a user post a new message, it's done via Ajax so the server returns a view with the posts information. That view is item.html.twig

So I have something like:

messages.html.twig

{% for item in posts %}
    &lt;div class="post"&gt;
         Posted by {{ item.author }}&lt;br&gt;
         {{ item.body }}
    &lt;/div&gt;
{% endfor %}


(well much more information in each posts of course)

item.html.twig

    &lt;div class="post"&gt;
         Posted by {{ item.author }}&lt;br&gt;
         {{ item.body }}
    &lt;/div&gt;


But the code is now duplicated and if I have to add a functionality or if I change my class names, I'll have to edit both of the views.

Would it be okay, in terms of performances, if I just included the item.html.twig in messages.html.twig like:

{% for item in posts %}
    {% include 'item.html.twig' with {item: item} %}
{% endfor %}


I don't know if there's a better solution so I would like to hear about ideas to improve my code.
I would strongly recommend you to go for the include solution. You will probably take a small performance hit, but that should not outweigh the benefits of having code that is much easier to maintain. Whenever you have to duplicate code, you are doing something wrong.

Also, if you find performance really important, may I suggest not sending the rendered (sub)view trough ajax. It would be much better to send just the data as JSON over the wire. It will be much smaller, and the server does not need to take time to render anything. You can then parse the JSON in your js to render the view there. There are templating languages for js that you could use, there is even a js version of twig (I haven't used it yet, so I don't know if it is any good, but I like the idea...)