M
M
Muhammad2015-06-27 11:35:40
HTML
Muhammad, 2015-06-27 11:35:40

Where to store HTML and CSS for JS?

For example, there is a bootstrap alert:

<div class="alert alert-success" role="alert">...</div>

and a few more styles to go with it. I need to use pure JS (without using template engines) when clicking on a button, add them to any block. What would be the best way to store these sections of code? Is this option correct:
<script id="entry-template" type="template">
  <div class="entry">
    <h1>{{title}}</h1>
    <div class="body">
      {{body}}
    </div>
  </div>
</script>

And what would be the best way to replace it with the values ​​I need?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Ineshin, 2015-06-27
@muhammad_97

Well, if you really really want to do without a template engine, then you can do this: jsfiddle.net/ph2xnbfv/1

var html =
    '<div class="entry">' +
    '<h1>{{title}}</h1>' +
    '<div class="body">' +
    '{{body}}' +
    '</div>' +
    '</div>';

var title = "Vasya";
var body = "Pupkin";

var result = html.replace("{{title}}", title);
result = result.replace("{{body}}", body);

console.log(result);

A
Alexander Petrov, 2015-06-27
@dzhiriki

Let me ask you: why don't you want to use template engines?
It's just that you give markup in a script as an example - this is already the beginning of using template engines :)
If you are confused by the weight of template engines, but you don't need logic in templates (and you just need to replace values), then you can use something very lightweight: https:// github.com/felixexter/tmpl.js

var html = $('#entry-template').html().tmpl({
  title: 'My title',
  body: 'My body'
})

Then paste it where you need it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question