Skip to content

Instantly share code, notes, and snippets.

@acro5piano
Last active September 21, 2016 07:13
Show Gist options
  • Save acro5piano/beb57cc57313e5a74f5b543657ba2350 to your computer and use it in GitHub Desktop.
Save acro5piano/beb57cc57313e5a74f5b543657ba2350 to your computer and use it in GitHub Desktop.
Bashでテンプレートエンジンっぽいものを作った ref: http://qiita.com/acro5piano/items/26de28485142eeac37b1
# Render a template file
#
# $ cat template.txt
# ==========================
# Hello, I'm {{ name }}.
# It's {{ wheather }} wheather today.
# ==========================
#
# $ util::render_template template.txt 'name=bashist&wheather=good'
# ==========================
# Hello, I'm bashist.
# It's good wheather today.
# ==========================
util::render_template() {
template_text="`cat $1`"
saveIFS=$IFS
IFS='=&'
parm=($2)
IFS=$saveIFS
declare -A params
for ((i=0; i<${#parm[@]}; i+=2)); do
template_text=`echo "$template_text" | sed "s/{{ ${parm[i]} }}/${parm[i+1]}/"`
done
echo "$template_text"
}
tree
|-- lib
| `-- util.sh
`-- test
|-- fixtures
| |-- test_include_asterisk.tpl.txt
| `-- test.tpl.txt
`-- test_util.bats
Hello, {{ name }}! Asterisk is *.
Hello, I'm {{ name }}.
It's {{ wheather }} wheather today.
#!/usr/bin/env bats
source './lib/util.sh'
@test "util::render_template with newline" {
expected="Hello, I'm bashist.
It's good wheather today."
actual="`util::render_template './test/fixtures/test_include_newline.txt' 'name=bashist&wheather=good'`"
[ "$expected" == "$actual" ]
}
@test "util::render_template with asterisk" {
expected="Hello, bashist! Asterisk is *."
actual="`util::render_template './test/fixtures/test_include_asterisk.txt' 'name=bashist'`"
[ "$expected" == "$actual" ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment