Blade模板中包括SVG内容

Blade模板中包括SVG内容

本文介绍了在Laravel 5 Blade模板中包括SVG内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel 5刀片服务器模板中包括SVG文件(位于资产文件夹中)的内容的最佳方法是什么?

What is the best way to include the contents of an SVG file (located in the assets folder) in a Laravel 5 blade template?

我不想使用图像/对象/嵌入标签,出于速度考虑,这应该是嵌入式SVG.

I don't want to use image/object/embed tags, this should be an inline SVG for reasons of speed.

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

I know I could use <?php file_get_contents("file.svg") ?> but is there a better way specific to Laravel/Blade?

为明确起见,该方法应适用于所有 SVG文件,包括以下文件.

to clarify, the method should work with all SVG files, including the one below.

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

推荐答案

类似于已接受的答案,但更加简洁(imo).

Similar to the accepted answer but a bit cleaner (imo).

使用laravel指令来扩展刀片,就像这样(在您的应用服务提供商中,如这里):

Use the laravel directive to extend blade, like so (in your App Service Provider, as outlined 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;
    });

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

Then use it in your blade like so:

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

这篇关于在Laravel 5 Blade模板中包括SVG内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 10:04