Shared Rails and JavaScript views - javascript

I'm a little confused as to why this isn't a more commonly addressed problem but here goes.
I have my Rails app which generates my views normally.
I have some dynamic content on the interface.
I want to make an AJAX call, return JSON, and populate the dynamic portions of the application. I would use a JS templating library to do this.
I DON'T want to make an AJAX call, have Rails process the view and send all the HTML back. I want the response to be JSON so cut down on processing and wire time.
The problem is that the HTML I'm generating dynamically is the same HTML I'm generating statically on page load by Rails (think AJAX pagination). The HTML is naturally in my ERB files. But when I generate more content (say, page 2), I obviously can't access the ERB files and need to duplicate the HTML in a JavaScript template file.
Is there a solution out there which allows me to share my views between Rails and JS? (I understand it's a little awkward to try to mix ERB with JS rendering...loops, conditionals, etc)
Do people usually settle for rendering HTML and sending it over the wire? Or, do they awkwardly execute JavaScript upon page load to render using JS templates?

I ran into the same problem in the past. I was able to solve it with Mustache: http://mustache.github.com/ At the time there was no easy way to setup mustache with rails so I had to code something together. It looks like now there is a lib for it here: https://github.com/goodmike/mustache_rails3
Update:
Looks like there is a nice gem now to accomplish it called stache: https://github.com/agoragames/stache

Related

What is the purpose of template engines in Java?

I'm an android developer and about two years and recently I've been thinking about building web applications. So I started researching about spring boot and everything is great. Then, I came across this thing called template engines (thymeleaf) which by definition separate your code from presentation.
What is confusing me is how can a backend server have html? should the presentation be handled by html, css and javascript in the front end? I even saw tutorials where they actually type in html code in their controller as return values.
My understanding is that the backend server exposes APIs for the frontend to use by using AJAX and the frontend will manipulate this data and present the information on the screen, why would a backend provide html code?
THank you
the frontend will manipulate this data
What front end? You mean the JavaScript code in the HTML page? Where did that come from? Oh yeah, the server.
It is the server that serves the HTML pages to the client, as well as any .js and .css files.
The server could provide static pages, and anything dynamic is handled by JavaScript. Or, the server could dynamically build the HTML page, using ... you guessed it ... a template engine.
You generally don't want JavaScript to build the page initially, just to use JavaScript for handling any dynamic behavior. Some pages don't even need any dynamic behavior.
Unless of course you're thinking about single-page applications (SPA), where there is only one root HTML page, and everything else is built client-side with JavaScript and AJAX calls, but most web applications are not SPAs.
Thymeleaf replaces JSP by providing HTML pages using a template engine. The controller requests the HTML file and Spring Boot provides that template after building it using the Model provided.
Thymeleaf is great because it allows you to rebuild templates on the fly. Lets say for example you're showing a users points to them on the front end, but maybe the points increase or decrease.
What you can do is build the template in the background using a Model. The Model reference is magically provided to the template provided which parses it.
#RequestMapping(...)
public String request(Model model) {
model.put("points", 5);
return "my-template.html"
}
Then use the Thymeleaf language to provide your object to the HTML file to be processed in the engine during runtime.
<html..>
<head>...</head>
<body>
<h1 th:text="${points}"></h1>
</html>
Spring Boots Template engine will build this in the background and present it to the user, but it will show the actual points to the end user! Hope this helps a tiny bit.
I know this question has been answered pretty effectively so far, but I want to add my two cents in as I work with Thymeleaf often.
The easiest way to think about a template engine is that it allows some dynamic development of html based on information passed to it by the controller method. This allows you to put logic in that normally wouldn't exist, or say display a certain section if a user is perhaps logged into admin.
If web pages were houses, html is the frame, css is the walls, Javascript is the lights and electricity, and a template engine would pretty much just be the architect designing the plans on the fly before the frame was built based on desires of the buyer of the house (user inputs).
OK, newer Apps and websites may just load/boot/open once and then pull or push data via AJAX requests, this is good, it saves traffic and it is fast.
But it has not always been like this and some Frameworks still don't build everything on small requests. Spring in Java or Symfony in PHP are MVC Frameworks and use template engines to build pages. This may sound a little outdated but there is still a lot of websites using this.
And if you build a web app for a customer with slow PCs or other devices and the page contents are performance heavy you might want to do as much work as possible on the server so that the user does not have to wait for long. And also you can cache the rendered pages. There is even server side rendering of react pages to e.g. make the initial page load faster...
With Java and Spring I did just use JSP I don't know thymeleaf. Just use what you like and maybe what is most supported/documented.
And building websites like this does not mean you cannot use AJAX, but if you use templates you need to think about what makes sense.
What is confusing me is how can a backend server have html?
The "back end" must have HTML, because that's what's delivered to, and rendered by, the client.
It may just be that the back end "server" is just a CDN delivering, say, an HTML/JS SPA, but there's still something delivering content to the browser.
That said: server-side rendering is still a thing, and has had a resurgence lately--a React app may have its initial rendering done on the server so again the client gets a page rendered with both HTML and associated data, and then starts acting like a normal SPA.
My understanding is that the backend server exposes APIs for the frontend to use by using AJAX and the frontend will manipulate this data and present the information on the screen, why would a backend provide html code?
Because something needs to run the JS to access those APIs.
Some history:
Browsers used to suck. JS used to be a neat add-on, sites were relatively static, and essentially all rendering was done on the server. The back end would get data from wherever it got data from and generate complete HTML pages, and there was little happening on the client side other than some form fields, maybe some validation, and that was about the extent of it.

Reload php page inside AngularJS

I have a AngularJS template where I embed dashboards.
With PHP I generate some code. The first time I visit the page in my AngularJS template all is working great. But the second time I visit the page I see the old PHP code.
AngularJS is not regenerating the PHP code which should be changing every time you visit it. How could I solve this?
I need my PHP code to generate a unique ticket to embed the dashboard properly.
I have tried this post: AngularJs: Reload page but it is not working.
Thanks.
AngularJS works in a way different to how you are thinking it works. Give your head a shake and prepare to think a little differently.
In an AngularJS app, the displayed HTML or DOM, a mix of tags and business data, is generated client-side (browser). It should not be generated server-side with PHP, as you are trying to do.
AngularJS creates the displayed HTML client-side based on your AngularJS code/instructions and data. Your code/instructions include Javascript and the AngularJS template. Templates should not contain business data, but only instructions on where the data should be placed to create the HTML (or DOM) that is displayed. These instructions are ng-bind, {{var}}, ng-repeat, etc.
Just as it does not repeatedly retrieve your Javascript code/instructions from the server, AngularJS does not repeatedly retrieve your template code/instructions from the server. It gets it once, caches it locally, and re-uses it whenever it needs to re-display that page.
Your AngularJS templates really should be static *.html files, just like your .js (and .css) are static files. Only under some really weird requirement should you ever need to dynamically generate AngularJS templates with PHP.
(Now, to get the business data needed by the template, you use AngularJS's $http service. This makes a call to your PHP server-side. Your PHP code returns just the data, wrapped in JSON, ... and NOT wrapped in HTML.)

templating in nodejs confused about several things

When it comes to templating my understanding is that you can do several things:
Serve static pages.
Pre Compile everything (jade to html) once and then serve the same thing to all.
At every request render everything and then serve.
Render static parts ahead of time (when app starts) and render dynamic parts at request.
Serve vanilla html and render dynamic part at request.
Send vanilla html + template and library(engine) and render at client.
What i want to do is number 5 and if not then 4. I don't want to rewrite all html, css etc. For the sake of just templating. I want to stick to html. But for part that needs to be dynamic i'd like templating. However if in case that this is not possible. I'd like to be able at least precompile the static part of the page and then compile user specific (dynamic) part at request.
I was looking into jade, but i can't figure out how would i do that? Is there a way, there should be, that i can type jade within html so only parts are dynamic are done in jade. I was told to compile jade, then append it to vanilla html. This is not ok. Because it requires me manually piece together html which isn't viable solution if you have lots of html and pages.
I hope everything is clear..if not leave a comment.

Include html files in an html file on a local file system?

I have a help system that is completely offline, no server, using file://.
I have one main page, with hundreds of line of html that represent many sections of the help system. I would like to stick each section in a html file and just include it. Unfortunately it seems like this is only possible with some nifty server side include techniques, with HTML5 (which I do not want to assume my users have), or with a nasty javascript hack where you copy your html file into js files with document.write calls for every line as written about here: Ways to include html in html.
What about something like handlebars.js or mustache.js? Can I use templating?
Since you don't want to use server-side includes, I would suggest using a static site generator (SSG).
If you are not familiar with SSG's, they allow you generate HTML pages from templates & includes (often Handlebars templates) and HTML, Markdown, JSON, or YAML, content using a CLI.
If you want to get started with an SSG, there are plenty of options, from Ruby based Jekyll, or Node.js based Assemble. In my opinion, Assemble is the best option and I would highly recommend it.

Is Single page application just one page using for entire web application?

I'm learning about single page application and after read document itself
I wonder that single page application pattern is just one page(e.g: html page) in web application using knockout with external template?
I mean ( i'm using MVC ):
-mywebsite
+ some js files
+ some css files
+ index.html
+ controllers
+ models
I hope someone can explain for me more about this pattern.Thanks.
Yes, you generally have a single HTML page that acts as a "shell" that has views of information loaded into that "shell". The JavaScript files act as the medium to call out to get this data, parse the data and apply templates to the data. Models, controllers, etc. allow for a module approach to the JavaScript structure, as opposed to spaghetti JavaScript code. CSS serves the same purpose as usual.
In my opinion, it is what pure AJAX applications were intended to be about 10 years ago, where a single page would load and then only requests to the server or services would load data, only performing partial page updates instead of posting back to the server to render (or re-render) the page (like WebForms does).
UPDATE:
The Single Page Application: KnockoutJS template incorporates KnockoutJS, but there are other options as detailed in Know a library other than Knockout?, which enumerates the features of each template in a grid for easy viewing.
Actually you can separate your application in to set of html files and java script files. What Single page application supposed to have is do all the application stuff without refreshing the browser. You can lazy load your views (html) and JavaScript whenever you need . I think you can start with a template or sample to get the idea of it.
you can get more details from John Papa
Here are some frmameworks which supports SPA
http://durandaljs.com/
http://www.asp.net/single-page-application/overview/introduction/knockoutjs-template
A single page application typically provides a shell in the form of a single page that invokes ajax calls to provide functionality. The key idea is that the shell doesn't refresh as a full page, but rather the content is refreshed through ajax calls that target sub sections of the shell.
One benefit of this model is that users don't have to deal with the disruptive user experience of refreshing the entire page and losing client side state.
Knockout can certainly be used as part of your design, but it's not directly part of the pattern.

Categories