Laravel blade @include 到 Javascript 变量中?
Laravel blade @include into a Javascript variable?
在 Laravel 5 blade 模板中,我有一个 <script>
部分。
在本节中,我需要将变量设置为来自另一个 blade 模板的字符串。
我试过类似的东西:
<script>
var a = "@include 'sometext.blade.php' ";
</script>
但这显然行不通。
此外,包含的 blade 可以同时包含单引号和双引号,因此需要以某种方式对它们进行转义,否则 Javascript 将无效。
有什么想法吗?
在使用 DataTables 时最终需要类似的功能,并且额外的操作 HTML 需要事后通过 jQuery 注入。
首先我created a helper function with this (from Pass a PHP string to a JavaScript variable (and escape newlines)):
function includeAsJsString($template)
{
$string = view($template);
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "[=10=]..'\")));
}
然后在您的模板中,您可以执行以下操作:
$('div.datatable-toolbar').html("{!! includeAsJsString('sometext') !!}");
包含 sometext.blade.php
blade 模板,转义引号并删除换行符。
在 Laravel 5 blade 模板中,我有一个 <script>
部分。
在本节中,我需要将变量设置为来自另一个 blade 模板的字符串。
我试过类似的东西:
<script>
var a = "@include 'sometext.blade.php' ";
</script>
但这显然行不通。
此外,包含的 blade 可以同时包含单引号和双引号,因此需要以某种方式对它们进行转义,否则 Javascript 将无效。
有什么想法吗?
在使用 DataTables 时最终需要类似的功能,并且额外的操作 HTML 需要事后通过 jQuery 注入。
首先我created a helper function with this (from Pass a PHP string to a JavaScript variable (and escape newlines)):
function includeAsJsString($template)
{
$string = view($template);
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "[=10=]..'\")));
}
然后在您的模板中,您可以执行以下操作:
$('div.datatable-toolbar').html("{!! includeAsJsString('sometext') !!}");
包含 sometext.blade.php
blade 模板,转义引号并删除换行符。