Create HTML tag from Javascript object

前端 未结 6 2054
清歌不尽
清歌不尽 2021-02-19 06:21

What is the best method to change this object

{
    src: \'img.jpg\',
    title: \'foo\'
}

into a valid HTML tag string like t

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-19 06:41

    If you are only doing one element, then this solution is overkill, but I thought I would post it anyway as I don't know what your project is.

    Have you considered a JavaScript template engine? I've been playing around with Swig lately, as it is quite lightweight, but there are many options. Basically, you create a template, pass a JavaScript object, and the compiled template is executed, returning a string of HTML.

    Example from Swig Documentation

    Template

    {{ pagename|title }}

      {% for author in authors %} {{ author }} {% else %}
    • There are no authors.
    • {% endfor %}

    JavaScript to Render Template

    var template  = require('swig');
    var tmpl = template.compileFile('/path/to/template.html');
    tmpl.render({ // The return value of this function is your output HTML
        pagename: 'awesome people',
        authors: ['Paul', 'Jim', 'Jane']
    });
    

    Output

    Awesome People

    • Paul
    • Jim
    • Jane

提交回复
热议问题