简体   繁体   中英

assign html snippet in javascript

There are times that I need to assign a html snippet to a javascript var, such as,

var homePage =
    '<div>' +
        '<div class="header"><h1>Page Slider</h1></div>' +
        '<div class="scroller">' +
                '<ul class="list">' +
                '<li><a href="#page1"><strong>Build Bot</strong></a></li>' +
                '<li><a href="#page2"><strong>Medi Bot</strong></a></li>' +
                '<li><a href="#page3"><strong>Ripple Bot</strong></a></li>' +
            '</ul>' +
        '</div>' +
    '</div>';

This can work good, but it makes editing a bit hard. May I know any framework can do this elegantly?

Use handlebars.js this is how is works:

Server side:

Send a JSON object back to javascript. I usually use something like this: echo json_encode(array('object_name'=>$obj));

HTML

  1. Create a container on your page. <div id="#my_template_container"></div>

Javascript:

usually in your AJAX success function:

  1. Parse your data into a JSON object:
    var my_obj= JSON.parse(data);
  2. Create a reference to the template:
    var tmpl = $("#my_layout").html();
  3. Use the Handlebars engine to compile the template:
    var theTemplate = Handlebars.compile(tmpl);
  4. Append the template to the HTML
    $('#my_template_container').html(theTemplate(my_obj));

Template

  1. Access your object in the template by it's name, in this example it would be : object_name the variable I assigned in my echo json_encode(array('object_name'=>$obj)) statement from PHP.
  2. Access properties of the object using {{Property_Name}} .
  3. To access properties of object children use the nested path operator: {{Propert_Name.ID}}

   <script id="my_layout" type="text/x-handlebars-template">
        {{#object_name}}
         '<div>' +
                '<div class="header"><h1>Page Slider</h1></div>' +
                '<div class="scroller">' +
                        '<ul class="list">' +
                        '<li><a href="#page1"><strong>{{property1}}</strong></a></li>' +
                        '<li><a href="#page2"><strong>{{property2}}</strong></a></li>' +
                        '<li><a href="#page3"><strong>{{property3}}</strong></a></li>' +
                    '</ul>' +
                '</div>' +
            '</div>';
        {{/object_name}}

        </script>

I created a very light plugin, just for the times, when you just want to use some html inside js, and do not require a lot of options provided my templating frameworks and thus want to avoid heavy js.

Coffee script

(($) ->
  utCache = {}
  $.fn.ut = (tmplID, obj) ->
    _tmpl = (str) ->
      fn = "var p=[]; p.push('" + str.replace(/[\r\t\n]/g, " ").replace(/'(?=[^%]*%>)/g, "\t").split("'").join("\\'").split("\t").join("'").replace(/<%=(.+?)%>/g, "',$1,'").split("<%").join("');").split("%>").join("p.push('") + "'); return p.join('');"
      new Function("o", fn)
    _getData = (ele) ->
      $(ele).html utCache[tmplID](obj)
    @each ->
      ele = this
      utCache[tmplID] = _tmpl($(tmplID).html()) unless utCache[tmplID]
      _getData ele
) jQuery

Javascript

(function($) {
  var utCache;
  utCache = {};
  return $.fn.ut = function(tmplID, obj) {
    var _getData, _tmpl;
    _tmpl = function(str) {
      var fn;
      fn = "var p=[]; p.push('" + str.replace(/[\r\t\n]/g, " ").replace(/'(?=[^%]*%>)/g, "\t").split("'").join("\\'").split("\t").join("'").replace(/<%=(.+?)%>/g, "',$1,'").split("<%").join("');").split("%>").join("p.push('") + "'); return p.join('');";
      return new Function("o", fn);
    };
    _getData = function(ele) {
      return $(ele).html(utCache[tmplID](obj));
    };
    return this.each(function() {
      var ele;
      ele = this;
      if (!utCache[tmplID]) {
        utCache[tmplID] = _tmpl($(tmplID).html());
      }
      return _getData(ele);
    });
  };
})(jQuery);

You can use it simply like,

$('#my-div').ut("#my-template", { name: 'jashwant'});

when we have following HTML:

<div id='my-div'></div>

<script type='javascript' id='my-template'>
  <p><%=o.name %> welcomes you !</p>
</script>

Do it with Javascript's document methods.

var topdiv = document.createElement('div');
var headerDiv = document.createElement('header');
var header = document.createElement('h1');
header.innerHTML = 'Page Slider';
headerDiv.appendChild(header);

// etc....

Or use templating.

Just use backslashes to escape line breaks.

Eg:

var homePage =
    '<div> \
        <div class="header"><h1>Page Slider</h1></div> \
        <div class="scroller"> \
                <ul class="list"> \
                <li><a href="#page1"><strong>Build Bot</strong></a></li> \
                <li><a href="#page2"><strong>Medi Bot</strong></a></li> \
                <li><a href="#page3"><strong>Ripple Bot</strong></a></li> \
            </ul> \
        </div> \
    </div>';

Use \\n\\ instead of \\ if you want to include the line breaks in the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM