プログラミング + アカデミック + 何か面白いこと

  1. Programming
  2. 22 view

[CoffeeScript]Very Tiny Template Engine

Template:

<script type="text/javascript">
people = [];
(function () {
{repeat}
people.push({
name: "#{people[index].name}"
});
{repeat}
})();
</script>

Expected Result:

<script type="text/javascript">
people = [];
(function () {
{repeat}
people.push({
name: "suzuki"
});

people.push({
name: "tanaka"
});

people.push({
name: "bob"
});

})();
</script>

Coffee Script’s main code:

class Tag

	constructor: (data, text) ->
		@validated = data
		@text = text
		
		@keywords = [
			/^numpeople$/
			/^people$/
			/^people\[[0-9]\].name$/
		]
				
	validate: (str) ->
		for keyword in @keywords
			if keyword.test(str)
				return true
		return false

	string_to_value: (str) ->
                # Syntax Sugar
		if str == 'names'
			names = []
			for people, i in @validated.people
				names.push "'#{people.name}'"
			names.toString()
		# Normal replace
                else
			if @validate(str)
				eval("this.validated." + str)
			else
				str

	replace: () ->
		# Replace repeatable line
		targets = @text.match(/{repeat}([\n\r]|.)*?{repeat}/)
		if targets != null
			target = targets[0]
			insert_line = target.substring(12,target.length-13)
			result = ""
			for item, i in @validated.items
				replaced_insert_line = insert_line.replace(/{index\+1}/g, i+1)
				replaced_insert_line = replaced_insert_line.replace(/index/g, i)
				result += replaced_insert_line
			@text = @text.replace(/{repeat}([\n\r]|.)*?{repeat}/, result)

		# Replace variable
		targets = @text.match(/#{.*?}/g)
		if targets != null
			for target in targets
				pattern = target.replace(/\[/g, '\\[')
				pattern = pattern.replace(/\]/g, '\\]')
				regex = new RegExp(pattern, 'g')
				@text = @text.replace(regex, @string_to_value(target.substring(2,target.length-1)))

	get_tag: () ->
		@text

exports.Tag = Tag

Programming recent post

  1. Install sbt 1.0.0 and run sample template

  2. [Machine Learning]Created docker image includ…

  3. [Node.js]How to write batch script with Node.…

  4. [Play][Scala]Develop Request Driven Batch Usi…

  5. [OpenCV][Ruby]Auto check web page design corr…

関連記事

PAGE TOP