tadm123
tadm123

Reputation: 8787

Passing Json data to HTML template

I'm new to web-development, I honestly don't know even what question to ask. So I'll just explain what I want to do.

I'm making a website that renders a random quote. I already selected an API for this:

$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
  $("body").append(a[0].content + "<p>— " + a[0].title + "</p>")
});

Which gives me:

Complexity is the enemy of reliability.

— Kyle Matthew Hansen

Now, I created a general skeleton in HTML to structure my website, how would I pass these json elements into my HTMl template so I can manipulate them?

So, I'm guessing I want to access the a[0].content and a[0].title elements in my HTML so I can place them where I want them and style them.

Thanks

Upvotes: 1

Views: 5876

Answers (2)

Satpal
Satpal

Reputation: 133403

As you have already created HTML, You can use jQuery templates

var item = {
  content: "Complexity is the enemy of reliability.",
  title: 'Kyle Matthew Hansen'
};
$("#myTemplate").tmpl(item).appendTo(".container");
.content {
  color: green
}
.title {
  color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

<script id="myTemplate" type="text/x-jquery-tmpl">
  <div>
    <div class="content">${content}</div>
    <span class="title">${title}</span>
  </div>
</script>
<div class='container'>
</div>

Upvotes: 1

mehulmpt
mehulmpt

Reputation: 16547

Do something like this:

<body>
...
<div id="quotes">

</div>
...
</body>

And JS:

$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
  var quote = a[0].content;
  var author = a[0].title;
  var quoteHTML = $('<div class="quote"><div class="quoteBody">'+quote+'</div><div class="quoteAuthor">'+author+'</div>';
  $('#quotes').append(quoteHTML);
});

And then in CSS, you can style all quotes with .quote, .quoteBody, .quoteAuthor, etc.

Upvotes: 2

Related Questions