Working with grails templates and the render method isn't that hard.
I worked with it for a while now.
It's okay for me to deal with the 'Convention over Configuration'. And so it is with the needed underscore "_" at the beginning of the filename of a template .gsp file.
I'm not that experienced with programming in general, I'm doing an apprenticeship as a 'IT-specialist for application development' since 2,5 years now. So my background knowledge isn't that big yet.
But I'd now really like to understand what exactly the purpose of that underscore is.
How's grails dealing with files with a leading underscore in comparison to those without it?
String view='/path/to/file'
def model= [template:view,instance:bean]
render(view:view, model:model)
this tells that template is '/path/to/_file.gsp' when it renders the template bit
when it renders view it looks for '/path/to/file.gsp'
so when you do render view it looks for files without underscore
when you do render template it looks for those with underscore
above example does both to explain how it works
As others have already pointed out the underscore indicates that the file is a template. However, the question still remains "what's the purpose?"
The purpose of a template is to provide a way to render a reusable fragment of view code. This allows you to compose very complex views (e.g. think functional decomposition). Templates aren't decorated by the sitemesh layout. This is very important when doing partial page updates with AJAX (or similar technology).
The documentation actually explains templates quite well.
Related
Just to distinguish between a view used inside a dialog or used in a foreach loop (customer details) ?
You don't need an underscore. It's just a convention, and MVC is very keen on using conventions.
Mike Brind has put this nicely in the question Why does Razor _layout.cshtml have a leading underscore in file name?:
Since layout pages in Web Pages are not intended to be served directly, they are prefixed with the underscore. And the Web Pages framework has been configured not to allow files with leading underscores in their names from being requested directly.
Besides that, I find it very helpful to use this convention to differentiate between full views and partial ones.
#Marius Schulz gives a nice reference, but then misses the point. Yes, the underscore helps to differentiate between full views and partial ones, but more importantly, it prevents partial views from being loaded directly by their URL, which could provide some potentially ugly results! (Like no css, for starters.)
EDIT: Mystere Man is right...what was I thinking? URLs in MVC point to controller/action, not to view.
Also, it is possible to mess things up and display a partial in a seperate window, so the naming convention does not prevent that. #Marius Schulz and I had the same misinterpretation of his quote.
The leading underscore is a useful convention to differentiate full and partial views, and I will continue to use it, but is is just a convention, not a functional difference.
I am trying to use ember.js in my Rails app.
Have a question specific to globalizing the handlerbars view template content.
Should I try to create myview.handlebars.erb and get the strings translated on the server side (havent tried this) or should I create seperate handlebars templates per each language (doesnt sound like really DRY unless there is a cleaner way)?
Whats the ideal way to go about it?
Did you get this working to your satisfactioin?
Another alternative (what we use at http://travis-ci.org) is i18n-js.
We like it because it lets you keep all your localizations in the same place (config/locales/[x].yml) and automatically adds them into your assets path.
Part of that DRY thing ;)
The syntax in your handlebars is pretty much the same, we just us a handlebars helper
Handlebars.registerHelper('i18n', function(key) {
return new Handlebars.SafeString(I18n.t(key))
});
and then {{i18n "path.to.translation"}} in the handlebars view.
Ember-I18n provides a solution: https://github.com/jamesarosen/ember-i18n
Let's say I have 2 MVC web projects (web1 and web2) and 1 project containing shared views (common) (using the razorgenerator of David Ebbo)
web1 and web2 both have a test.cshtml file. Several blocks of code in both test.cshtml files are exactly the same.
I'm trying to find out if it's possible to share a declarative helper (#helper) between several cshtml files which are in DIFFERENT projects. So putting a cshtml file in my App_Code does not help (I would need to have 1 in each web project, which is obviously not what I want).
I know I could create a bunch of shared partial views in my 'common' project, but it seems kinda overhead to create 20 cshtml files that each contains a very small portion of html.
I know I can create a standard helper method (static string GenerateAPieceOfHtml(this HtmlHelper helper, ....)), but there I loose the ease of writing html as you can do it in a cshtml file.
For a short while I thought I bumped into an answer that would allow me to do it. But as I wrote in a comment, that code did not compile for me.
I hope my question is clear :)
[Update]
As csharpsi asks in a comment.. I did try out the code from the other post, but it did not spit out any HTML for me. Since I started to think that that answer should probably do the trick since it has 13 upvotes, I decided to give it a second try..
Again I didn't get any output, but then I tried it a little bit different.. and success!
I was trying this (which doesn't spit out any html on the page):
#{ new Test().DoSomething(Model); }
This is the version that DOES WORK:
#{
var html = new Test().DoSomething(Model);
#html
}
Other version that works:
#(new Test().DoSomething(Model))
What should I do with this question? Delete it? Write an answer myself?
Why are you trying to use razor helper for this anyway ? Razor helpers are one-particular-viewengine hack, your application shouldnt rely on them on many places (even amongst different websites). In this case, be sure to use standard MVC way - HTML helper. These you can easily share between websites, for example you can make your own class library full of them.
On my previous projects built with usage of Zend Framework I extensively used Zend_view's "Action View" helper. It basically allows to initiate a separate cycle of request->dispatch ti action->view_rendering from a view script.
Here is the link to an appropriate page of zend framework reference guide (search for "Action View Helper").
This helper is quite a convenient way to work with widgetized content for example on pages with portal layout where you can stuff a page with different widgets (like advertising blocks, currency informers etc).
Although such an approach negatively affects response time of the page as it involves a lot of additional routing/dispatching activity, it allows to organizes widget code and views scripts into a rational structure. One widget is just a controller action, with linked view script.
Unfortunatelly, I have not found any similar view helpers in Rails.
Is there any way to elegantly solve this task in Rails?
In Rails, the render method of ActionController takes a Hash as arguments and outputs a simple string. You can use this in your view like so:
<%= render :partial => "shared/widgets/_#{widget.widgettype.name}", :collection => #current_user.widgets %>
In this case Rails will iterate through the list of #current_user.widgets, find a widget partials in "app/views/shared/widgets/_widgettypename.html.erb", and call the partial for each attached widget.
For further reading on Rails partials, see the ActionView::Partials documentation.
It seems that I've found an answer to my questions myself. It is "render_component" rails plugin. There is also a fork which apparently supports Rails3.
I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags?
Thanks!
-fREW
My advice - if it's small pieces of HTML (a couple of tags) don't worry about it. More than that - think about partials (as pulling strings of html together in a helper is a pain that's what the views are good at).
I regularly include HTML in my helpers (either directly or through calls to Rails methods like link_to). My world has not come crashing down around me. In fact I'd to so far as to say my code is very clean, maintainable and understandable because of it.
Only last night I wrote a link_to_user helper to spits out html with normal link to the user along with the user's icon next to it. I could have done it in a partial, but I think link_to_user is a much cleaner way to handle it.
I don't see that there's anything wrong with it. The majority of the rails helpers generate HTML code (which is their purpose) - to me this implies that's what you're supposed to do yourself.
There is however the ever-present issue of code readability. If you have a helper which just builds a big string of raw HTML, then it's going to be hard to understand. While it's fine to generate HTML in helpers, you should do it using things like content_tag, and render :partial rather than just return %Q(<a href="#{something}">#{text}>)
This isn't a full answer to your question, but you can create html in your tags via the content_tag method. My guess as to why would be cleanliness of code.
Also, content_tag allows you to nest tags in blocks. Check out this blog post on content_tag.
On Rails 3 you can use *html_safe* String method to make your helper methods return html tags that won't be escaped.
As mentioned before, helpers are generally thought to be used as business logic, for doing something that drives view code, but is not view code itself. The most conventional place to put things that generate snippets of view code is a partial. Partials can call a helper if needed, but for the sake of keeping things separated, it's best to keep business in the helper and view in the partial.
Also, bear in mind this is all convention, not hard and fast rules. If there's a good reason to break the convention, do what works best.
I put html into partials usually.
Think about semantics. If you put html in a string, you lose the semantic aspect of it: it becomes a string instead of markup. Very different. For example, you cannot validate a string, but you can validate markup.
The reason I wanna put html in a helper instead of partial (and how I found this thread) is terseness. I would like to be able to write =hr instead of =render 'hr'.
To answer the question I didn't ask ;-) : to un-escape HTML in a helper, try this
def hr
raw '<hr />'
end