How to add snippets of 'dynamic code' HTML with JavaScript / jQuery

5

Generally when we want to list data in the front-end tags using back-end tags <%= %> or others. The deadlock I came across was, "How to do this in jQuery?".

To explain it better, I'm developing a blog based on Wordpress. As I'm better at front-end , it made sense to do the CSS and HTML part. Already the content part, I was instructed to use the JSON API from Wordpress.

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>

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

In 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 that was great, it turns out that the front-end does not allow me to have only a standard formatting for all publications, some are more elements than others. Well, I honestly think this is typical of a "bricklayer." Is there any way to automate this process?

EDIT

Following the tip of @bfavaretto (Mustache.js), 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 holds my templatePost , that is, whenever I need to use it it is only change the variable of the dynamic data, in my case it is post , and use the Mustache.to_html() passing the appropriate parameters. This way I will create the other templates and only change the variable post .

Maybe it's not the right way to use it, but it solves the problem by the hour.

    
asked by anonymous 14.06.2014 / 05:16

1 answer

5

Following the bfavaretto tip , I tested the implementation of mustache.js . > in a WordPress theme and look like this:

1) No functions.php 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 some of the templates of the theme, single.php in my test. The format is:

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

<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: For use with the JSON REST API (WP API) plugin and developed by a Core Developer), it is necessary to make a small change in the object received to be able to loop:

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