简体   繁体   中英

Rails partial best practice

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:

  1. 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.

  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM