Skip to content
Eugene Lazutkin edited this page Dec 9, 2013 · 13 revisions

Type: String Default value: see below

A string value that is used to generate individual entries corresponding to original source images in a sprite's CSS file. The alternative way to supply a template is to use options.templateFile. If both are specified at the same time, options.template supersedes options.templateFile.

This string is a template understood by Underscore's template() or Lo-Dash's template(). When it is instantiated following variables are available:

  • name -- a fully-qualified (absolute) name of an original image.
  • shortName -- a relative name of an original image as it was generated by grunt.
  • className -- a CSS class name generated from a short name by replacing dots and file separators with underscores with a prefix (see options.classPrefix.
  • x -- a horizontal position of the image in a sprite in pixels.
  • y -- a vertical position of the image in a sprite in pixels.
  • w -- a width of the image in a sprite in pixels.
  • h -- a height of the image in a sprite in pixels.
  • url -- a relative or absolute path of a generated sprite. See options.absolute for details.

Default

The default value is:

.<%= className %> { background: url(<%= url %>) -<%= x %>px -<%= y %>px no-repeat; width: <%= w %>px;  height: <%= h %>px; }

The actual value is one line, and it has a newline symbol at the end.

The same information split on several lines for your convenience:

.<%= className %> {
  background: url(<%= url %>) -<%= x %>px -<%= y %>px no-repeat;
  width: <%= w %>px;
  height: <%= h %>px;
}

Examples

Example #1

A fragment of CSS file generated with the default template:

.sprite_x16_address_16_png {background: url(sprite1.png) -1568px -144px no-repeat; width: 16px; height: 16px;}
.sprite_x16_block_16_png {background: url(sprite1.png) -1584px -144px no-repeat; width: 16px; height: 16px;}
...

Example #2

A custom template used for debugging:

grunt.initConfig({
  tight_sprite: {
    // describe my sprite
    icons: {
      options: {
        template: [
          ".<%= className %> {",
          "  /* image: <%= name %> */ ",
          "  /* short: <%= shortName %> */ ",
          "  background-position: -<%= x %>px -<%= y %>px; ",
          "  width: <%= w %>px; ",
          "  height: <%= h %>px;",
          "",
          "}",
          "\n"
        ].join("\n")
      },
      cwd: "images/icons",
      src: ["**/*.png"],
      dest: "images/icons.png"
    }
  }
})

It will produce a following fragment:

.sprite_x16_address_16_png {
  /* image: /home/project/images/icons/16x16/address.png */
  /* short: 16x16/address.png */
  background-position: -1568px -144px;
  width: 16px;
  height: 16px;
}

.sprite_x16_block_16_png {
  /* image: /home/project/images/icons/16x16/block.png */
  /* short: 16x16/block.png */
  background-position: -1584px -144px;
  width: 16px;
  height: 16px;
}
...

Clone this wiki locally