{% extends "demo/_layout" %}

{% set pageTitle = "Twig Template Caching on Forms | Extras" %}

{# Replace 'freeformTwigCache' with your form handle #}
{% set demoFormHandle = "freeformTwigCache" %}

{% block content %}

    {% set form = freeform.form(demoFormHandle, { formattingTemplate: pageTemplateFile }) %}

    <div class="freeform-page-heading">
        <h2>Twig Template Caching on Forms</h2>
        <p>The following example shows how to refresh the CSRF token and other parts of Freeform when using Twig Caching on a template that contains a form.</p>
    </div>

    {% if form %}

        {% cache for 10 minutes %}

            <div class="freeform-notice{{ colorMode == "dark" ? " freeform-notice-dark" }}">
                <p>Randomly Generated Number</p>
                <h4>{{ random(5000, 10000) }}</h4>
                <p><small>(this number will stay the same for 10 minutes, proving the cache is still present for the rest of the page)</small></p>
            </div>

            {{ form.render }}

        {% endcache %}

        {# Script for updating the form's Hash and CSRF token #}
        <script>
            // Find the corresponding Form
            var form = document.querySelector('form');

            // Locate and update the Hash input
            var formHashInput = form.querySelector('input[name=formHash]');
            formHashInput.setAttribute('value', '{{ form.hash }}');

            // Locate and update the CSRF input
            var csrfInput = form.querySelector('input[name={{ craft.app.config.general.csrfTokenName|e('js') }}]');
            csrfInput.value = '{{ craft.app.request.csrfToken|e('js') }}';
        </script>

    {% else %}

        <div class="freeform-error{{ colorMode == "dark" ? " freeform-notice-dark" }}">
            <p>You must rename your form handle to <code>{{ demoFormHandle }}</code> for this part of the demo to work.</p>
        </div>

    {% endif %}

    {# Instructions to get this page working correctly #}
    <div class="extras-instructions">
        <h4>This page will not display correctly until...</h4>
        <p>
            In order to view this page live, you'll need to make some adjustments to this template or your test form:
            <ol>
                <li>Rename your test form handle to <code>{{ demoFormHandle }}</code> or adjust the form handle name inside this template to match your test form.</li>
            </ol>
        </p>
    </div>

{% endblock %}
