Grails: render file from assets folder into gsp - grails

I use require.js in a Grails project. There are a couple of single JavaScript files containing the require.js modules defined with define.
There is also a *.gsp file which generates the require.js config and the entry point starting with require() as there is some dynamic configs to be generated. It looks somehow like this:
<%# page contentType="application/javascript;charset=UTF-8" %>
require(['a', 'b'], function(a, b){
...
var a = ${controllerPropertyA};
...
some functions
...
});
In my layout I integrate require.js like this:
<script data-main='http://example.com/exampleController/dynamicGenerateMethod?domain=xyz.com' src='http://example.com/assets/require.js'></script>
All the modules a , b, and so on are asynchronously loaded by require.js. Now I would like to bundle them into a single file - I could use the require.js optimize tool but I prefer to use the assets-pipeline. This works as far as that I get all modules bundled into a single optimized-modules.js which is available on http://example.com/assets/optimized-modules.js.
The question: I would like to have the optimized JavaScript code in the dynamically rendered GSP file. So how can I inject the optimized-modules.js file into the GSP I'm dynamically rendering? I already thought about a tag defined in the tag library so that my *.gsp would look like
<%# page contentType="application/javascript;charset=UTF-8" %>
<g:renderFile file="/assets/optimized-modules.js" />
require(['a', 'b'], function(a, b){
...
var a = ${controllerPropertyA};
...
some functions
...
});
and the tag definition somehow like that:
def g:renderFile = { attrs, body ->
def filePath = attrs.file
if (!filePath) {
throwTagError("'file' attribute must be provided")
}
//out << filePath
out << request.servletContext.getResource(filePath).file
//out << grailsResourceLocator.findResourceForURI(filePath).file.text
//out << grailsApplication.mainContext.getResource(filePath).file.text
//out << Holders.getServletContext().getResource(filePath).getContent()
//IOUtils.copy(request.servletContext.getResourceAsStream(filePath), out);
}
But I can't get the content of the minified optimized-modules.js which was done by the assets-pipeline plugin on startup. Any thoughts on this?

Ok, I finally found it out by myself:
Instead of using the grailsResourceLocator I had to use the assetResourceLocator which is the way to go if you try to access assets resources.
My tag definition now looks like:
def renderFile = { attrs, body ->
def filePath = attrs.file
if (!filePath) {
throwTagError("'file' attribute must be provided")
}
ServletContextResource bar = (ServletContextResource)assetResourceLocator.findAssetForURI(filePath)
String fileAsPlainString = bar.getFile().getText("UTF-8")
out << fileAsPlainString
}
That way I can inject a compile assets javascript file into my GSP - perfect!

Related

Rails Image assets in AngularJS Directive and template

I have Rails 4 Application with AngularJS using these gems:
gem 'angularjs-rails'
gem 'angular-rails-templates'
gem 'asset_sync'
It works great with a template like this:
<img ng-controller='LikePostController'
ng-dblclick='like(post);'
ng-src='{{post.photo.standard}}'
class='lazy post_photo pt_animate_heart'
id='post_{{post.id}}_image'
/>
The Image render correctly. However in my other js
petto.directive('ptAnimateHeart', ['Helper', function(Helper){
linkFunc = function(scope, element, attributes) {
$heartIcon = $("#heart_icon");
if($heartIcon.length == 0) {
$heartIcon = $("<img id='heart_icon' src='/assets/feed.icon.heart.png' alt='Like' /> ");
$(document.body).append($heartIcon);
}
element.on('dblclick', function(event){
$animateObj = $(this);
Helper.animateHeart($animateObj);
});
}
return {
restrict: 'C',
link: linkFunc
}
}])
I got 'assets/feed.icon.heart.png' was not found error from the browser console. I have feed.icon.heart.png located under app/assets/feed.icon.heart.png.
ps: Forget to mention I use assets sync gem to host assets in amazon s3. the image worked well in development but not in production.
Hardcoded asset links only work in development because in production the assets get precompiled. Which means, amongst other things, the filename changes from:
my_image.png
into something like this (it adds and unique md5-hash):
"my_image-231a680f23887d9dd70710ea5efd3c62.png"
Try this:
Change the javascript file extension to: yourjsfile.js.erb
And the link to:
$heartIcon = $("<img id='heart_icon' src='<%= image-url("feed.icon.heart.png") %>' alt='Like' /> ");
For better understanding The Asset Pipeline — Ruby on Rails Guides
You can define the following method somewhere in your helpers, e.g. in app/helpers/application_helper.rb:
def list_image_assets(dir_name)
path = File.expand_path("../../../app/assets/images/#{dir_name}", __FILE__)
full_paths = Dir.glob "#{path}/**.*"
assets_map = {}
full_paths.each do |p|
original_name = File.basename p
asset_path = asset_path p[p.index("#{dir_name}")..-1]
assets_map[original_name] = asset_path
end
assets_map.to_json
end
One can modify the method to work with any assets you wish, not just the ones located in subdirs of app/assets/images as in this example. The method will return a map with all the original asset names as keys and their 'compiled' names as values.
The map returned can be passed to any angular controller via ng-init (not generally recommended, but appropriate in this case):
<div ng-controller="NoController" ng-init="assets='<%=list_image_assets "images_dir_name"%>'"></div>
To make the assets really usable in angular, define a new $scope valiable in the controller:
$scope.$watch('assets', function(value) {
if (value) {
$scope.assets = JSON.parse(value);
}
});
Having this in the $scope, it's possible to use assets names as usual, in e.g. ng-src directives, and this won't brake after the precompile process.
<img ng-src={{::assets['my_image.png']}}/>
Just do the following:
app.run(function($rootScope,$location){
$rootScope.auth_url = "http://localhost:3000"
$rootScope.image_url = $rootScope.auth_url + "/uploads/user/image/"
});
In controller inject dependency for $rootScope
and in views
<img ng-src="{{user.image.url}}" width="100px" height="100px">
Note: It's working great in Rails API and it assumes that you've user object available so that it could specify the correct image in the /uploads/image/ directory

How can I load static content into a gsp page?

We have a grails project that is templated to produce two different sites. The sites have two different Frequently Asked Question pages but we would like to keep the template the same. We were thinking about including two different *.groovy files that have variables in them with the questions and then map those variables to a gsp page. Or maybe two different *.gsp files and the right one gets included at startup.
What is the best way to include the static content into the gsp page while reusing as much code as possible and how would I go about doing it?
Let me know if you need more information.
Grails have the concept of templates to reuse your view code. For example:
*grails-app/views/book/_bookTemplate.gsp*
<div class="book" id="${book?.id}">
<div>Title: ${book?.title}</div>
<div>Author: ${book?.author?.name}</div>
</div>
grails-app/views/book/someView.gsp
<g:render template="bookTemplate" model="[book: myBook]" />
grails-app/views/book/anotherView.gsp
<g:render template="bookTemplate" model="[book: myBook]" />
So you can use the render tag in any GSP that needs to use your template.
It is kind of late but I was looking for the answer myself. While there is no direct way to have insert static file in Grails, there are various ways you could accomplish so. From controller to custom tag. There is a code for custom tag:
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class HtmlTagLib {
// to be used in gsp like <html:render file="WEB-INF/some-static-file.txt"/>
// file param is relative to web-app folder
static namespace = 'html'
private static final Logger log = LoggerFactory.getLogger(HtmlTagLib .class)
def render = { attrs ->
String filePath = attrs.file
if (!filePath) {
log.error("'file' attribute must be provided")
return
}
String applicationPath = request.getSession().getServletContext().getRealPath( filePath )
def htmlContent = new File(applicationPath).text
out << htmlContent
}
}
Credits to Dónal on Rendering HTML files in Grails

ASP.net MVC static resource bundles and Scripts.Render()

I'm trying to implement some static resource improvements into my ASP.net MVC 4 project (VB.net) by changing how static resources such as javascript and css files are retrieved.
I've been following this link (ASP.NET & MVC 4: Cookieless domain for bundling and static resources ) to help accomplish this but I've come across an issue whereby unbundled javascript and css files are not rendered.
Normally when rendering .js or .css bundles you use the following:
#Scripts.Render("~/bundles/jquery")
This will then render each script tag separately in the ~/bundles/jquery bundle when in development mode, and render a single script tag pointing to the minified bundle when in production.
According to the link above, when the scripts are bundled into a single file, you can use the following line:
<script src="#Url.StaticContent("~/bundles/jquery")" type="text/javascript"></script>
This works fine for me for bundled files since the src property is valid and the StaticContent function is able to change the src URL. But when in development mode, the bundled file does not exist as no bundling takes place and all scripts are rendered seperately to the browser by #Scripts.Render and so this method does not work.
Does anyone know if it is possible to create an extension method for the Scripts helper that will accomplish what I need, or am I going to have to do something like this?
#If Misc.IsLocalDev Then
#Scripts.Render("~/bundles/jquery")
Else
#<script src="#Url.StaticContent("~/bundles/jquery")" type="text/javascript"></script>
End If
I managed to find a solution to this problem, so hopefully by putting it up here for all to see this will help others with a similar problem that I had.
Working off the same idea as the workaround I posted in my original question, I created 2 new helper functions to help generate the necessary Script and Style references in my views...
Scripts
<ExtensionAttribute()> _
Public Function RenderScripts(helper As HtmlHelper, async As Boolean, ParamArray Paths() As String) As IHtmlString
If Misc.IsLocalDev Then
Return Optimization.Scripts.Render(Paths)
Else
Dim url As UrlHelper = New UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes)
Dim html As String = ""
For Each Path In Paths
If async = True Then
html = html & "<script async src=""" & url.StaticContent(Path) & GetAppVersionSuffix() & """ type=""text/javascript""></script>"
Else
html = html & "<script src=""" & url.StaticContent(Path) & GetAppVersionSuffix() & """ type=""text/javascript""></script>"
End If
Next
Return New HtmlString(html)
End If
End Function
So instead of using:
#Scripts.Render("~/bundles/jquery")
I replaced the calls with:
#Html.RenderScripts(False, "~/bundles/jquery")
A few notes on the above method...
I added an async parameter to the function call to allow me to utilise modern browser aynsc scripts.
The GetAppVersionSuffix() function call returns the assembly version which is appended to the end of the scripts source as ?v=1.2.3.4 for example. This ensures that the browser gets a new copy of the scripts and style-sheets when a new version is released.
The Misc.IsLocalDev function is a special function I use to change the way certain parts of the web application behave when I'm developing on my local machine. In this case, it ensures that unbundled scripts and styles are rendered instead of minified/bundled ones to ease debugging.
Styles
<ExtensionAttribute()> _
Public Function RenderStyles(helper As HtmlHelper, ParamArray Paths() As String) As IHtmlString
If Misc.IsLocalDev Then
Return Optimization.Styles.Render(Paths)
Else
Dim url As UrlHelper = New UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes)
Dim html As String = ""
For Each Path In Paths
html = html & "<link href=""" & url.StaticContent(Path) & GetAppVersionSuffix() & """ rel=""Stylesheet"" />"
Next
Return New HtmlString(html)
End If
End Function
So again, instead of using:
#Styles.Render("~/Content/Style")
I replaced the calls with:
#Html.RenderStyles("~/Content/Style")
I hope this is useful to someone!

Loading static resources from a Grails custom tag, with disposition: 'head'

I'm trying to write a Grails custom tag that (among other things) triggers inclusion of a resource, so something like <myTags:view name="foo"/> would load, say, js/views/foo.js. And I want it loaded with disposition: 'head'.
I could use <r:external/>, but that wouldn't put it in the <head>, it would just produce an inline <script/> tag. And I could use <r.script/>, but that doesn't let me reference a path; I'd have to have my custom tag read the file and dump it to out.
Now, if foo.js was its own module, I could do something like: r.require([module: 'foo']), but it's not; part of the point of this is that I don't want to have to declare all of these files in ApplicationResources.groovy. But maybe I could have ApplicationResources.groovy create the modules programmatically, by reading through the available files -- is that possible? Or is there a better way?
I ended up going in the direction of having ApplicationResources.groovy create modules programmatically, so the custom tag can use <r:require/>.
The idea is, for each Backbone view, under web-app/myApp/views, there's a Backbone view in a .js file, and a Handlebars template in a .handlebars file (with the same name, by convention). The .handlebars file gets declared as an ordinary module, but gets precompiled by the Handlebars-Resources plugin.
Some code in ApplicationResources.groovy finds all the views and creates corresponding resource modules:
GrailsApplication grailsApplication = Holders.getGrailsApplication()
File viewsDir = grailsApplication.parentContext.getResource("myApp/views").file;
if (viewsDir.exists() && viewsDir.isDirectory() && viewsDir.canRead()) {
String[] viewsJS = viewsDir.list().findAll { name ->
name.endsWith("View.js")
}
String[] views = viewsJS.collect { name ->
name.substring(0, name.length() - ".js".length())
}
for (view in views) {
"${view}" {
dependsOn 'backbone', 'backbone_relational', 'handlebars'
resource url: "dpg/views/${view}.handlebars",
attrs: [type: 'js'],
disposition: 'head'
resource url: "dpg/views/${view}.js",
disposition: 'head'
}
}
}
Then the taglib:
class ViewsTagLib {
static namespace = "myApp"
def view = { attrs ->
r.require(module: "${attrs.name}View")
out << "<${attrs.tagName} id='${attrs.id}'></${attrs.tagName}>"
}
}
Invoking it in a GSP:
<myApp:view tagName="div" name="foo" id="foo1"/>
<myApp:view tagName="div" name="foo" id="foo2"/>
Produces:
<html>
<head>
...
<!--
Automagically generated modules (included only once).
Should put these in the same bundle, but handlebars-resources
gets confused.
-->
<script src="/myApp/static/bundle-bundle_fooView_handlebars.js"
type="text/javascript" ></script>
<script src="/myApp/static/bundle-bundle_fooView_head.js"
type="text/javascript" ></script>
</head>
<body>
...
<div id="foo1"></div> <!-- backbone placeholder for 1st view instance-->
<div id="foo2"></div> <!-- backbone placeholder for 2nd view instance-->
</body>
</html>
It's not pretty but the mess is mostly hidden, and it should cut down considerably on boilerplate and on opportunities to forget to add magic strings to multiple files.

Way to organize client-side templates into individual files?

I'm using Handlebars.js, and currently all my templates live inside script tags which live inside .html files housing dozens of other templates, also inside script tags.
<script type="text/template" id="template-1">
<div>{{variable}}</div>
</script>
<script type="text/template" id="template-2">
<div>{{variable}}</div>
</script>
<script type="text/template" id="template-3">
<div>{{variable}}</div>
</script>
...
Then I include this file on the server-side as a partial.
This has the following disadvantages:
A bunch of templates are crammed into HTML files.
Finding a given template is tedious.
I'm looking for a better way to organize my templates. I'd like each each template to live in its own file. For example:
/public/views/my_controller/my_action/some_template.html
/public/views/my_controller/my_action/some_other_template.html
/public/views/my_controller/my_other_action/another_template.html
/public/views/my_controller/my_other_action/yet_another_template.html
/public/views/shared/my_shared_template.html
Then at the top of my view, in the backend code, I can include these templates when the page loads, like this:
SomeTemplateLibrary.require(
"/public/views/my_controller/my_action/*",
"/public/views/shared/my_shared_template.html"
)
This would include all templates in /public/views/my_controller/my_action/ and also include /public/views/shared/my_shared_template.html.
My question: Are there any libraries out there that provide this or similar functionality? Or, does anyone have any alternative organizational suggestions?
RequireJS is really good library for AMD style dependency management. You can actually use the 'text' plugin of requireJS to load the template file in to your UI component. Once the template is attached to the DOM, you may use any MVVM, MVC library for bindings OR just use jQuery events for your logic.
I'm the author of BoilerplateJS. BoilerplateJS reference architecture uses requireJS for dependency management. It also provides a reference implementations to show how a self contained UI Components should be created. Self contained in the sense to handle its own view template, code behind, css, localization files, etc.
There is some more information available on the boilerplateJS homepage, under "UI components".
http://boilerplatejs.org/
I ended up using RequireJS, which pretty much let me do this. See http://aaronhardy.com/javascript/javascript-architecture-requirejs-dependency-management/.
I use a template loader that loads the template using ajax the first time it is needed, and caches it locally for future requests. I also use a debug variable to make sure the template is not cached when I am in development:
var template_loader = {
templates_cache : {},
load_template : function load_template (params, callback) {
var template;
if (this.templates_cache[params.url]){
callback(this.templates_cache[params.url]);
}
else{
if (debug){
params.url = params.url + '?t=' + new Date().getTime(), //add timestamp for dev (avoid caching)
console.log('avoid caching url in template loader...');
}
$.ajax({
url: params.url,
success: function(data) {
template = Handlebars.compile(data);
if (params.cache){
this.templates_cache[params.url] = template;
}
callback(template);
}
});
}
}
};
The template is loaded like this:
template_loader.load_template({url: '/templates/mytemplate.handlebars'}, function (template){
var template_data = {}; //get your data
$('#holder').html(template(template_data)); //render
})
there's this handy little jquery plugin I wrote for exactly this purpose.
https://github.com/cultofmetatron/handlebar-helper

Resources