demo.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * JavaScript Templates Demo
  3. * https://github.com/blueimp/JavaScript-Templates
  4. *
  5. * Copyright 2013, Sebastian Tschan
  6. * https://blueimp.net
  7. *
  8. * Licensed under the MIT license:
  9. * http://www.opensource.org/licenses/MIT
  10. */
  11. /* global document, tmpl */
  12. ;(function () {
  13. 'use strict'
  14. var templateInput = document.getElementById('template')
  15. var dataInput = document.getElementById('data')
  16. var resultNode = document.getElementById('result')
  17. var templateDemoNode = document.getElementById('tmpl-demo')
  18. var templateDataNode = document.getElementById('tmpl-data')
  19. function renderError (title, error) {
  20. resultNode.innerHTML = tmpl(
  21. 'tmpl-error',
  22. {title: title, error: error}
  23. )
  24. }
  25. function render (event) {
  26. event.preventDefault()
  27. var data
  28. try {
  29. data = JSON.parse(dataInput.value)
  30. } catch (e) {
  31. renderError('JSON parsing failed', e)
  32. return
  33. }
  34. try {
  35. resultNode.innerHTML = tmpl(
  36. templateInput.value,
  37. data
  38. )
  39. } catch (e) {
  40. renderError('Template rendering failed', e)
  41. }
  42. }
  43. function empty (node) {
  44. while (node.lastChild) {
  45. node.removeChild(node.lastChild)
  46. }
  47. }
  48. function init (event) {
  49. if (event) {
  50. event.preventDefault()
  51. }
  52. templateInput.value = templateDemoNode.innerHTML.trim()
  53. dataInput.value = templateDataNode.innerHTML.trim()
  54. empty(resultNode)
  55. }
  56. document.getElementById('render').addEventListener('click', render)
  57. document.getElementById('reset').addEventListener('click', init)
  58. init()
  59. }())