LoginSignup
7
5

More than 5 years have passed since last update.

PugでSVGをインクルードする

Last updated at Posted at 2017-01-25

includeを使ってSVGを埋め込み

includeを使ってSVGファイルをHTMLの内部に埋め込見ます。

example.pug
div: div: include cc.svg

pugコマンドでhtmlを生成します。--pretty は出力するHTMLを整形するオプションです。

HTMLを生成
node_modules/.bin/pug example.pug --pretty

このようなHTMLが出力されます。

<div>
  <div><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="43" fill="none" stroke="#000" stroke-width="9"/>
  <path d="M50,42c-6-9-20-9,-25,0c-2,5-2,11,0,16c5,9,19,9,25,0l-6-3c-2,5-9,5-11,0c-1-1-1-9,0-10c2-5,9-4,11,0z"/>
  <path d="M78,42c-6-9-20-9,-25,0c-2,5-2,11,0,16c5,9,19,9,25,0l-6-3c-2,5-9,5-11,0c-1-1-1-9,0-10c2-5,9-4,11,0z"/>
</svg>

  </div>
</div>

サイズを指定してSVGを埋め込み

includeを使ってSVGファイルをHTMLの内部に埋め込見ます。

サイズ指定の出力
div: div(style="width: 30px"): include cc.svg

このようなHTMLが出力されます。

<div>
  <div style="width: 30px;"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="43" fill="none" stroke="#000" stroke-width="9"/>
  <path d="M50,42c-6-9-20-9,-25,0c-2,5-2,11,0,16c5,9,19,9,25,0l-6-3c-2,5-9,5-11,0c-1-1-1-9,0-10c2-5,9-4,11,0z"/>
  <path d="M78,42c-6-9-20-9,-25,0c-2,5-2,11,0,16c5,9,19,9,25,0l-6-3c-2,5-9,5-11,0c-1-1-1-9,0-10c2-5,9-4,11,0z"/>
</svg>

  </div>
</div>

div タグのスタイルが指定されています。div でなくてもブロック要素であれば大丈夫です。

CSSでサイズを指定してSVGを埋め込み

埋め込んだSVGのサイズはCSSでも指定できます。

example.pug
link(href="example.css" type="text/css" rel="stylesheet")
div: div.include_svg: include cc.svg

example.css
.include_svg {
    width: 30px;
}

このようなHTMLが出力されます。

<link href="example.css" type="text/css" rel="stylesheet"/>
<div>
  <div class="include_svg"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="43" fill="none" stroke="#000" stroke-width="9"/>
  <path d="M50,42c-6-9-20-9,-25,0c-2,5-2,11,0,16c5,9,19,9,25,0l-6-3c-2,5-9,5-11,0c-1-1-1-9,0-10c2-5,9-4,11,0z"/>
  <path d="M78,42c-6-9-20-9,-25,0c-2,5-2,11,0,16c5,9,19,9,25,0l-6-3c-2,5-9,5-11,0c-1-1-1-9,0-10c2-5,9-4,11,0z"/>
</svg>

  </div>
</div>

CSSで指定されているのでそのサイズが使われます。

あとがき

使用したpackage.jsonを載せておきます。

{
  "name": "include-svg",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "pug": "^2.0.0-beta7",
    "pug-cli": "^1.0.0-alpha6"
  }
}

Qiita記事には埋め込みSVGが使えないようでした。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5