Kontynuujemy naukę popularnego frameworka PHP Symfony. Tym razem pobawimy się twigiem i templatkami. Do dzieła.

Tworzymy obok index.html.twig plik dice.html.twig:

{% extends 'base.html.twig' %}

{% block title %}Hello HelloController!{% endblock %}

{% block body %}
<style>
    .example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
    .example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>

<div class="example-wrapper">
    <h1>Dice Roll</h1>
</div>
{% endblock %}

Ok, teraz route:

#[Route('/dice', name: 'app_dice', methods: ['GET', 'HEAD'])]
public function dice(): Response
    {
        $player = random_int(1,6);
        $computer = random_int(1,6);

        return $this->render('hello/dice.html.twig', [
            'player' => $player,
            'computer' => $computer
        ]);
    }

Teraz interpolacja zmiennych:

{% extends 'base.html.twig' %}

{% block title %}Hello HelloController!{% endblock %}

{% block body %}
<style>
    .example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
    .example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>

<div class="example-wrapper">
    <h1>Dice Roll</h1>
    <p>Your roll: {{ player }}</p>
    <p>Computer roll: {{ computer }}</p>
</div>
{% endblock %}

Ok, działa. Teraz if-else:

{% extends 'base.html.twig' %}

{% block title %}Hello HelloController!{% endblock %}

{% block body %}
<style>
    .example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
    .example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>

<div class="example-wrapper">
    <h1>Dice Roll</h1>
    <p>Your roll: {{ player }}</p>
    <p>Computer roll: {{ computer }}</p>

    {% if player > computer %}
            <p>You win</p>
    {% elseif player < computer %}
            <p>You lose</p>
    {% else %}
            <p>Draw</p>
    {% endif %}
    
</div>
{% endblock %}

Tak działa if-else w twigu.