在 Laravel 5 Blade 模板中包含 SVG 内容

Including SVG contents in Laravel 5 Blade template

将 SVG 文件(位于资产文件夹中)的内容包含在 Laravel 5 blade 模板中的最佳方法是什么?

我不想使用 image/object/embed 标签,出于速度原因,这应该是内联 SVG。

我知道我可以使用 <?php file_get_contents("file.svg") ?> 但是有更好的特定于 Laravel/Blade 的方法吗?

编辑:澄清一下,该方法应该适用于所有 SVG 文件,包括下面的文件。

<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg">
<path stroke="red" fill="#00f" d="M10 10h100v100H10z"/>
</svg>

View Composer 方法

我最终在服务提供商中使用了视图编辑器。

在服务提供商的boot()方法中:

// Wildcard view composer
view()->composer('*', function($view) {
    // Instantiate new DOMDocument object
    $svg = new DOMDocument();
    // Load SVG file from public folder
    $svg->load(public_path('images/logo.svg'));
    // Add CSS class (you can omit this line)
    $svg->documentElement->setAttribute("class", "logo");
    // Get XML without version element
    $logo = $svg->saveXML($svg->documentElement);
    // Attach data to view
    $view->with('logo', $logo);
});

在我看来:

<!-- Echo unescaped SVG content -->
{!! $logo !!}

我正在使用 DOMDocument,因为它允许我删除不应该在 HTML.

中的 XML 版本元素

CSS class 不是必需的,但可以让我用另一个 HTML 元素包装徽标以进行样式设置。

如果您只需要特定 Blade 部分中的徽标,例如 header,您可以写

view()->composer('header', function($view) {});

http://laravel.com/docs/5.0/views#view-composers
https://laracasts.com/series/laravel-5-fundamentals/episodes/25

Blade部分方法

这种方法不是最佳实践,因为这种代码不应该真正出现在视图中。然而,它非常简单,而且比在每个视图中添加 PHP 代码要好得多。

使用以下代码创建一个新的部分(比如说 logo.blade.php):

<?php
// Instantiate new DOMDocument object
$svg = new DOMDocument();
// Load SVG file from public folder
$svg->load(public_path('images/logo.svg'));
// Add CSS class (you can omit this line)
$svg->documentElement->setAttribute("class", "logo");
// Echo XML without version element
echo $svg->saveXML($svg->documentElement);
?>

您现在可以通过像这样包含部分内容在 blade 模板中使用 SVG 图像:

@include('logo')

这可行,这是我能想到的最简单的方法:

{!! file_get_contents('images/icon.svg') !!}

为什么不将 svg 放入 blade 模板中?

resources/views/icons/dashboard.blade.php

然后使用 blade 语法添加您的视图?

@include('icons.dashboard')

与已接受的答案类似,但更清晰一些 (imo)。

使用 laravel 指令扩展 blade,就像这样(在您的应用服务提供商中,如 here 所述):

    \Blade::directive('svg', function($arguments) {
        // Funky madness to accept multiple arguments into the directive
        list($path, $class) = array_pad(explode(',', trim($arguments, "() ")), 2, '');
        $path = trim($path, "' ");
        $class = trim($class, "' ");

        // Create the dom document as per the other answers
        $svg = new \DOMDocument();
        $svg->load(public_path($path));
        $svg->documentElement->setAttribute("class", $class);
        $output = $svg->saveXML($svg->documentElement);

        return $output;
    });

然后像这样在您的 blade 中使用它:

        <div class="Login__image Login__cloud">
            @svg('cloud.svg', 'Cloud')
        </div>