Skip to content

Instantly share code, notes, and snippets.

@pascalduez
Created March 30, 2014 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pascalduez/9879588 to your computer and use it in GitHub Desktop.
Save pascalduez/9879588 to your computer and use it in GitHub Desktop.
A Sass micro-templating function.
// ----
// Sass (v3.3.7)
// Compass (v1.0.0.alpha.18)
// ----
// A Sass micro-templating function.
// -----------------------------------------------------------------------------
// @param [string] $format
// @param [arglist | map] $args
// -----------------------------------------------------------------------------
// @return [string]
@function template($format, $args...) {
$result: $format;
@each $key, $value in keywords($args) {
$token: "{{#{$key}}}";
$length: str-length($token);
$index: str-index($result, $token);
@if $index {
$result: if($index > 1, str-slice($result, 1, $index - 1), "")
+ $value
+ str-slice($result, ($index + $length));
@if str-index($result, $token) {
$result: template($result, $args...);
}
}
}
@return $result;
}
[test] {
arglist: template("Hello {{surname}}, {{name}}.", $surname: Jules, $name: Verne);
map: template("Hello {{surname}}, {{name}}.", (surname: Jules, name: Verne)...);
loop: template("{{name}} {{name}} {{name}}", $surname: Jules, $name: Verne);
graceful: template("{{names}} {{name}} {{surname}} {{surnames}}", $surname: Jules, $name: Verne);
}
[test] {
arglist: "Hello Jules, Verne.";
map: "Hello Jules, Verne.";
loop: "Verne Verne Verne";
graceful: "{{names}} Verne Jules {{surnames}}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment