在JQuery .html()调用中包含一个Twig模板并删除新行

Including a Twig template in a JQuery .html() call and remove new lines

本文关键字:Twig 新行 删除 包含一 html JQuery 调用      更新时间:2023-09-26

我想创建一个对话框,它将是另一个Twig文件的内容。在JQuery调用中,我有:

$('<div></div>')
    .html('{% include "folder/file.html.twig" %}')
    .dialog({....

在file.html.twig中有新行,所以当放入.html调用时,它会失败,因为.html调用不允许新行。如果有一种方法可以使用来自Twig的替换来摆脱所有新行,那么当我使用:

时,可能会起作用。
$('<div></div>')
    .html('{% include "folder/file.html.twig"|replace({"'n":""}) %}')
    .dialog({....

它替换路径外的任何新行(不存在的),而不是呈现的内容。

您可以使用filter标记来应用过滤器,而不是使用管道。

$('<div></div>')
    .html('{% filter replace({"'n":""})%}{% include "folder/file.html.twig" %}{% endfilter}')
    .dialog({....

然而,代替替换,使用json_encode过滤器将HTML转换为字符串,而不仅仅是将其放在引号之间。这也可以防止在包含引号的HTML中出现问题。

$('<div></div>')
    .html({% filter json_encode %}{% include "folder/file.html.twig" %}{% endfilter %})
    .dialog({....

尝试使用反划符

$('<div></div>')
.html(`{% include "folder/file.html.twig" %}`)
.dialog({....
模板文字

嗯,这当然是在JavaScript中混合小枝html输出的问题的例子,这很容易变得非常混乱,非常快-从经验来看。

尽管如此,你可以通过将包含的模板暴露为渲染控制器来解决这个问题,这样你就可以更容易地在纯PHP中准备响应->getContent(),即

{{渲染(控制器("AppBundle:文件夹:文件"))}}

....
Class Folder{
    ....
    public function fileAction(){
        ....
        $included_template_content = $this->renderView("folder/file.html.twig");
        // Process Content for javascript using php functions
        return new Response($included_template_content);
    }
    ....
}
....

或者,如果你想避免额外的子请求,你可以探索在Twig扩展

您可以使用ajax来完成此操作,如:

public function yourAction(Request $request)
{
    $template =  $request->isXmlHttpRequest() ? 'template_xhr.html.twig' : 'template.html.twig';
    return $this->render($template);
}

和ajax:

$.ajax({ url : 'url', success : function(data) { 
          $("#texte").html(data)
   })

使用无空格标签。它去掉了所有的空格,所以你的代码和内容不会受到影响,但它会全部显示在一行中:

$('<div></div>')
    .html('{% spaceless %}{% include "folder/file.html.twig" %}{% endspaceless %}')
    .dialog({....