Created
March 23, 2017 19:55
-
-
Save agustik/0b79d9bdf3929d6e845700669a955e2c to your computer and use it in GitHub Desktop.
Render template, great for old jquery apps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| <div class="foobar" id="torender"> | |
| <div class="adf"> | |
| <h4>{{name}} the {{job.title}} like {{hobby}}</h4> | |
| </div> | |
| </div> | |
| */ | |
| function renderTemplate(template, object){ | |
| if (!template) return; | |
| object = object || {}; | |
| var matchRegex = new RegExp(/\{\{[a-zA-Z0-9\s\.]*\}\}/g); | |
| var keys = template.match(matchRegex) || []; | |
| keys.forEach(function (a){ | |
| var templateKey=a.replace(/\s|\{|\}/g, ''); | |
| var value = getDescendantProp(object, templateKey) || ""; | |
| template = template.replace(a, value); | |
| }); | |
| return template; | |
| function getDescendantProp(object, descendantKey) { | |
| if (descendantKey.indexOf('.') === -1){ | |
| return object[descendantKey] | |
| } | |
| var arr = descendantKey.split("."); | |
| while(arr.length && (object = object[arr.shift()])); | |
| return object; | |
| } | |
| } | |
| jQuery.fn.extend({ | |
| render: function(object) { | |
| var template = $(this).html(); | |
| var renderedTemplate = renderTemplate(template, object); | |
| return $(this).html(renderedTemplate); | |
| } | |
| }); | |
| var element = $('#torender').render({ | |
| name : 'agustik', | |
| hobby : 'iceclimbing', | |
| job : { | |
| title : 'system administrator' | |
| } | |
| }); | |
| // or get the rendered template | |
| // element.html(); | |
| // oooor .... html = renderTemplate($('torender').html(), { foo : "bar" }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment