首页 > 解决方案 > 更新部分页面

问题描述

我有一个项目,我可以在其中添加元素并选择它们(它是模板创建者)。

模板创建者页面

基本上,我通过为添加的每个元素创建输入列表的 div 并根据是否选择元素设置 a display: noneor ,从而使一切正常工作。display: block

这可行,但如果我创建了很多元素,页面可能会充满不可见的 div,我正在寻找一种通过 AJAX 更新“元素添加”和“元素单击”的输入的方法。

另外,我用 Symfony 做了这个项目。现在我有一个_inputs.html.twig文件,其中有一个我所有输入的 div,其中 id 是在调用视图时指定的。

{% block body %}
<div id="inputs_{{ id }}" style="display: none;"><div class="form-floating p-2">
        <input id="{{ id }}_name" class="form-control bg-primary text-light">
        <label class="text-light">Nom</label>
    </div><hr><div class="form-floating p-2">
        <input id="{{ id }}_alignement" class="form-control bg-primary text-light">
        <label class="text-light">Alignement</label>
    </div><hr><div class="form-floating p-2">
        <input id="{{ id }}_font_size" class="form-control bg-primary text-light">
        <label class="text-light">Taille de police</label>
    </div><hr><div class="form-floating p-2">
        <input id="{{ id }}_bold" class="form-control bg-primary text-light">
        <label class="text-light">Gras</label>
    </div><hr><div class="form-floating p-2">
        <input id="{{ id }}_prefix" class="form-control bg-primary text-light">
        <label class="text-light">Préfixe</label>
    </div><hr><div class="form-floating p-2">
        <input id="{{ id }}_path" class="form-control bg-primary text-light">
        <label class="text-light">Chemin</label>
    </div><hr></div>
{% endblock %}

它基本上是我的所有输入,带有元素 ( {{ id }}) 的 id。

问题是我发现了很多不同的函数,我知道我需要在控制器的返回中调用一个函数(我将从 AJAX 请求和我的“元素单击”和“元素添加”事件中调用它)。

return $this->??????('render_inputs', [
        'id' => $id,
    ]);

我是否需要使用 renderBlock、renderView 或其他任何东西?

我只需要更新页面的正确部分,还需要存储不同输入的值(当我选择一个元素时,在输入中输入一些内容,我需要能够检索我输入的内容)。

看起来可以从标题中解决我的问题,但页面会刷新(这对我不起作用)。

标签: javascriptphpjquerysymfonytwig

解决方案


你是对的,你应该能够用函数解决这个问题renderBlock。该函数renderBlock位于类Template中,因此您首先需要加载模板才能使用该函数

$template = $twig->load('template.html');
$template->renderBlock('render_inputs', [
    'id' => $id,
]);

通常我会在我的块中放置一个容器,因此我可以轻松地更新所述块的 HTML,例如

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    </head>
    <body>
        <button type="button" id="refresh">Refresh</button>
        {% block some_block_name %}
        <section id="some_block_name">
            Lorem ipsum
        </section>
        {% endblock %}
        <script>
        $(function() {
            $(document).on('click', '#refresh', function() {
                $.get('http://www.example.com/ajax/update.php', function(html) {
                    $('#some_block_name').html(html);
                });
            });
        });
        </script>
    </body>
</html>

推荐阅读