How to add HTML dynamic code snippets with Javascript/jQuery

Asked

Viewed 5,113 times

5

Usually when we want to list data on front-end using the tags of back-end<%= %> or others. The stalemate I’ve come across now was: "How to do this in jQuery?".

To explain better, I am developing a blog based on Wordpress. How I am better at front-end, it was easy to do the CSS and HTML part. Already the content part, I was instructed to use the JSON Wordpress API.

In my case, a blog post has this format/structure:

<div class="post-container">
    <span class="post-title">Título</span>
    <div class="post-texto">
        Lorem Ipsum  Lorem Ipsum Lorem Ipsum Lorem Ipsum
    </div>
    <span class="author">Chico Bioca</span>
</div>

Since the API consumption returns me a JSON, I use the jQuery function to catch the object. Therefore, it is extremely convenient that the structure of the publication only appears when it exists. Otherwise the structure will be displayed empty or with wrong content.

This way I do the following:

$(document).ready(function (){
    $.getJSON('http://localhost/wordpress/?json=1&callback=?')
        .success(function(data) {
            var i;
            for (i = 0; i < data.count; i++)
                    $('.post-content').append(" <div class='post-container'>" +
                                                    "<span class='post-title'>"+ data.posts[0].title +"</span>" +
                                                    "<div class='post-texto'>"+ data.posts[0].content +"</div>" +
                                                    "<span class='author'>"+ data.posts[0].author +"</span>" +
                                                "</div>");
            }
        });
});

If that were all it would be great, but it turns out front-end does not allow me to have only a standard format for all publications, some consist of more elements than others. Well, honestly I find this very typical of a "bricklayer". Is there any way to automate this process?

EDIT

Following the @bfavaretto (Mustache.js) tip, I developed the following solution:

'use strict';

var templatePost = "<div class='box post-1 col-lg-75'>" +
                        "<img src='images/photo-post-1.png' alt=''>" +
                        "<div class='date-box bg-pink'>" +
                            "<div class='date'>{{date}}</div>" +
                            "<div class='post-category bg-video'></div>" +
                        "</div>" +
                        "<span class='post-title'>" +
                            "{{title}}" +
                        "</span>" +
                    "</div>" +
                    "<div class='post-texto-container col-lg-75'>" +
                        "<span class='post-titulo'>{{title}}</span>" +
                        "<div class='texto'>" +
                            "{{content}}" +
                        "</div>" +
                        "<div class='autor bg-pink'>" +
                            "<span class='por-texto'>por </span><span class='autor-texto'>{{author}}</span>" +
                        "</div>" +
                        "<div class='fb-container'>" +
                            "<div class='fb-comments' data-href='http://www.example.com.br' data-width='100%' data-numposts='3' data-colorscheme='light'></div>" +
                        "</div>" +
                    "</div>";

$(document).ready(function (){
    $.getJSON('http://localhost/wordpress/?json=1&callback=?')
        .success(function(data) {
            var post = {
                title: data.posts[0].title,
                content: data.posts[0].content,
                date: data.posts[0].date,
                author: data.posts[0].author.nickname
            };

            var html = Mustache.to_html(templatePost, post);
            $('.content-post').html(html);
        });
});

In case I have a variable that keeps mine templatePost, that is, whenever I need to use it is only change the variable of dynamic data, in my case it is post, and use the function Mustache.to_html() passing the appropriate parameters. This way I will create the other templates and change only the variable post.

Maybe it is not the correct way to use, but for now solves the problem.

  • 2

    I would use a template engine like http://handlebarsjs.com/ or https://github.com/janl/mustache.js

  • Want to teach me how to use it? : 3

  • Who knows tomorrow, today I can’t...

  • @bfavaretto I have a little problem in the data layout, specifically the data from "{content}}". Wordpress brings as content the HTML related to the post, IE, tags are displayed in the post and not interpreted. Have to give me a helping hand? :,]

  • 1

    Hi @Phellipe. In mustache, use 3 keys instead of two for variables where HTML should not be escaped: {{{content}}} instead of {{content}}.

1 answer

5


Following the tip from the bfavaretto, tested the implementation of mustache.js in a Wordpress theme and stays like this:

1) No functions.php we load the required Javascript files (jQuery, mustache.js and our script):

add_action( 'wp_enqueue_scripts', 'carrega_o_bigode' );
function carrega_o_bigode() {
    wp_register_script( 'mustach', get_stylesheet_directory_uri() . '/js/mustache.js' );
    wp_enqueue_script( 'bigode', get_stylesheet_directory_uri() . '/js/bigode.js', array( 'jquery', 'mustach' ) );
}

2) In any of the templates of the theme, single.php in my test. The format is:

{{#loop}}
    {{item}}
    {{{item-com-html}}}
    {{sub.item}}
{{/loop}}

and stay like this in the template:

<div id="target">Carregando...</div>
<script id="template" type="x-tmpl-mustache">
    {{#posts}}
    <div class="post-container">
        <h2 class="post-title">{{title}}</h2>
        <div class="post-texto">
        {{{content}}}
        </div>
        <span class="author">{{author.name}}</span>
    </div>
    {{/posts}}
</script>

3) And finally, our script bigode.js:

jQuery(document).ready(function($) {
    var template = $('#template').html();
    Mustache.parse(template);   // optional, speeds up future uses

    function loadData( data ) {
        var rendered = Mustache.render(template, data);
        $('#target').html(rendered);
    }

    // Usando o plugin http://wordpress.org/plugins/json-api/
    $.getJSON('http://plugins.dev/api/?json=1&callback=?').success(loadData);
});

PS: To use with the plugin JSON REST API (WP API) (more recent and developed by a Core Developer), it is necessary to make a small change in the received object in order to make the loop:

var rendered = Mustache.render(template, {posts: data} );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.