Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created November 26, 2012 12:19
Show Gist options
  • Save bloodyowl/4147922 to your computer and use it in GitHub Desktop.
Save bloodyowl/4147922 to your computer and use it in GitHub Desktop.
String#compile

String#compile

Has been added in Craft.js 1.1.7

Note : Uses Craft.js

Description

Fills placeholders in a string with data.

Usage

// with object
myString.compile(object)

// with string
myString.compile(string)

// with arguments
myString.compile(arg1, arg2, arg3 )

// with array
myString.compile(array) 

Note

{{*}} outputs the string passed at only argument.

Examples

"Hello {{firstName}} {{name}}!".compile({firstName : "John", name : "Smith"})
"Hello John Smith!"

"Hello John {{*}}!".compile("Smith")
"Hello John Smith!"

// accepts nesting
"Hello {{person.firstName}} {{person.name}}!".compile({person : {firstName : "John", name : "Smith"}})
"Hello John Smith!"

"Hello {{0}} {{1}}!".compile("John","Smith")
"Hello John Smith!"

"Hello {{0}} {{1}}!".compile(["John","Smith"])
"Hello John Smith!"
Object.extend(String.prototype, {
compile : function(object) {
if(arguments.length > 1) object = Array.convert(arguments)
return this.replace(/\{\{([\w\*\.]*?)\}\}/g, function(path, match){
var split = match.split(".")
if(typeof object == "string"){
if(match == "*") return object
else return ""
}
return split.fold(function(previous, actual){
return actual in previous ? previous[actual] : ""
}, object)
})
}
})
@fuadsaud
Copy link

Really nice.

Is Craft,js really necessary. As far as I can see it could be easily implemented with vanilla js :\

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment