I have a rails app that uses a开发者_运维知识库 twitter library to pull in tweets and display them one by one in my view using jquery. I am a little unsure of what the best way to transporting the tweets over from the controller to the view is though. The two ideas I have are:
Get back the twitter json in the controller/model, pass it to the view using jquery and then constructing the html with dom building methods.
Get back the twitter json in the controller/model, render a partial that displays a list of tweets with html and passing over that html partial with jquery.
Is one of these methods better than the other? Is there a completely better way of doing this?
Any help would be great!
You don't have to pass data to a view and then render to JSON. You can just do this in your controller:
render :json => tweets
I think this is a perfect use case for the official jQuery Templates plugin. The main function, tmpl
, has lots of great examples of how to use it.
I'll try to quickly summarize an example from their documentation. Basically, you put an HTML template inside script
tags like this:
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li><b>${Name}</b> (${ReleaseYear})</li>
</script>
Then, you get the data in a JSON object and pass it into the tmpl
function like this:
// movies contains your JSON data
$("#movieTemplate").tmpl(movies).appendTo("#movieList");
This example assumes that you have a ul
element with the id movieList and it appends an li
element to the list for every movie found in the movies
variable.
The movies variable would look something like this:
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
partials would make the result indexable if you wanted to build html on the page directly.
the javascript + json idea should be easier to implement but not by much.
精彩评论