Skip to content

Instantly share code, notes, and snippets.

@KittyGiraudel
Last active September 15, 2015 09:12
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 KittyGiraudel/43260fde78cd7326e26f to your computer and use it in GitHub Desktop.
Save KittyGiraudel/43260fde78cd7326e26f to your computer and use it in GitHub Desktop.
Generated by SassMeister.com.
// ----
// libsass (v3.2.5)
// ----
/// Replace `$search` with `$replace` in `$string`
/// @author Hugo Giraudel
/// @link http://sassmeister.com/gist/1b4f2da5527830088e4d Original gist
/// @param {String} $string - Initial string
/// @param {String} $search - Substring to replace
/// @param {String} $replace ('') - New value
/// @return {String} - Updated string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
/// Micro-templating function in Sass; replace tokens in `$template` with their value in `$data`
/// @author Hugo Giraudel
/// @param {String} $template - The template string containing tokens wrapped in double braces
/// @param {Map} $data - The data to be injected in place of the tokens
/// @return {String}
/// @example scss
/// $template: 'Hello {{addressee}}! I’m {{sender}}.';
/// $data: ('addressee': 'world', 'sender': 'Hugo');
/// $foo: template($template, $data);
/// // $foo -> "Hello world! I’m Hugo."
@function template($template, $data) {
@each $key, $value in $data {
$token: '{{#{$key}}}';
$tmpl: $template;
$template: str-replace($template, $token, inspect($value));
@if $template == $tmpl {
@warn 'The token `#{$token}` cannot be found in the template string.';
}
}
@return $template;
}
// -------
// Example
// -------
$template: 'Hello {{addressee}}! I’m {{sender}}.';
$data: (
'addressee': 'world',
'sender': 'Hugo',
);
.test {
content: template($template, $data);
}
@charset "UTF-8";
.test {
content: "Hello world! I’m Hugo.";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment