Tech Tips

  1. Uncategorized
  2. 139 view

[CoffeeScript]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

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

PAGE TOP