Componette

Componette

milo

milo / embedded-svg v1.3.0

Macro for embeding SVG into HTML.

download-cloud-line composer require milo/embedded-svg

Example

<h1>
    Publications
    {embeddedSvg 'icons/help.svg',
        class => 'help-icon',
        data-toggle => 'popover',
        data-content => 'This is a list of your publications for last 5 years.'
    }
</h1>

Result HTML code may look like:

<h1>
    Publications
    <svg xmlns="..." class="help-icon" ...>
        ... content of help.svg file ...
    </svg>
</h1>

Purpose

This is a single purpose helper library with a macro definition for Latte, the PHP templating engine. It loads SVG source file and embed it into HTML code in compile time.

Motivation for this is possibility to stylize SVG by CSS then. It is not (easily) possible with SVG linked as an image like <img src="https://raw.github.com/milo/embedded-svg/HEAD/icons/help.svg">.

Installation

Require library by Composer:

composer require milo/embedded-svg

Register extension in your config.neon and configure it:

extensions:
    embeddedSvg: Milo\EmbeddedSvg\Extension

embeddedSvg:
    baseDir: %wwwDir%/img

Configuration

There are some other optional options:

embeddedSvg:
    # change name of the macro
    macroName: svgIcon

    # pretty format SVG content (indent tags)
    prettyOutput: yes

    # default <svg> tag attributes, for example
    defaultAttributes:
        class: embedded
        height: 30px
        width: null

    # callbacks called when SVG loaded from file
    onLoad:
        - [SVGSanitizer, sanitize]

    # bitmask of LIBXML_* flags for DOMDocument::load() method
    libXmlOptions: (integer)

You can load the extension more then once. In this case, change macro name by macroName option.

Option defaultAttributes is a XML attributes list for generated <svg> tag. These are merged. The precedence is (higher to lower):

  • macro tag attributes
  • default attributes
  • attributes of <svg> tag loaded from file

If the attribute value is null, it is not rendered. You can unset attributes from SVG file in that way.

Callback added into onLoad event is called when SVG contents is successfully loaded into DOM. Its signature is:

function (DOMDocument $dom, Milo\EmbeddedSvg\MacroSetting $setting) {
    ...
}

Caveats & Limitations

Because embeddedSvg is a macro, it is compiled into PHP only once and then is cached. So, when you change the macro configuration, probably in NEON, you have to purge Latte cache.

  • v1.3.0 Released version 1.3.0

    • simplified Latte 3 compilation
    • fixed var overwriting by loop
  • v1.2.0 Released version 1.2.0

    • Latte v3 support
  • v1.1.0 Released version 1.1.0

    • fixed compatibility with Nette DI v3
  • v1.0.0 Released version 1.0.0

price-tag-2-line

Badges

guide-fill

Dependencies

php (>=7.1.0)
ext-dom (*)
latte/latte (^2.4.0)
Componette Componette felix@nette.org