I'm having a little issue here, we are bussy with our internship and are still learning so sorry in advance for some "stupid" questions.
We have a Haml file where we make use of datamapper for our Database.
For static views based on our data, we make use of datamapper-code lines in haml.
But now I wanted to use a Javascript variable, who's located in the pageload function, to use this as a parameter with our datamapper code lines in haml.
In our javascript:
$(document).ready(function(){
var ctrpersiteid = $.cookie('sitedata');
Part of our Haml file where we want to use our variable ctrpersiteid
- Interface.all(:router_id => getRouterId(ctrpersiteid)).each do |interface|
%h3 #{interface.name}
So is there any way that I could use my Javascript variable in the haml file as parameter for our function ?
The short answer is no. Javascript is only executed in the clients browser, so there's no way to access it from your server-side haml template.
Related
I'm trying to figure out how to organize my javascript/django code.
So far I used to put my javascript page specific code in the same file. i.e I embed javascript in a <script> tag inside the template.
This creates a lot of mess when my JS code become large:
- django template variables {{var}} inside my JS code does not look well,
- I get an error when I try to minify it with tools like this one: http://jscompress.com/ ,
- And I just try to separate them as much as possible.
Today, in my embeded <script> tag my JS code looks like:
var app = {
func: function() {
// can I use the {% url %} tag here ?
$.post('/url/', {csrfmiddlewaretoken:'{{csrf_token}}', something:'value'} )
},
jsonFromServer: '{{pythonDict|safe}}', // I need this data structure,
};
As you can see, there are some values I need to pass form django to javascript, the most common is the csrftoken, for ajax requests. But sometimes I also pass a json dictionary that is needed for the app itself. Sometimes I want to pass the server time as well.
I'm thinking of moving the JS code to a separate file, I read that it is better way to organize like that. But I can't see how it is possible in a normal django app, without django have to render the .js files. And I believe it is better the JS file won't be served by django?
So how could I organize my JS without too much django code in it ?
I Don't know if it's "beautiful" but usually, I organize my code like that when it's about make web dev in MVC:
I put my <script> tag in the template of my page.
I write my js in an external file, traditionally in the /static/JS/my_template_name.js
As my gobal layout can have some JS code too, I make a great use of the JS modules: https://medium.freecodecamp.com/javascript-modules-a-beginner-s-guide-783f7d7a5fcc#.bjf4xwuq4
Usually, I don't have to do that.
When I need var from server in my js code, I make some Ajax calls.
But if you really want to process like that, I can suggest you to do something like this in your template:
<script>
var from_server = {{vars_from_server}};
</script>
Normally, if you pass a variable named vars_from_server to your template it will replace the placeholder between the script tags. Just think to format "vars_from_server" in a correct JS way.
After that, you will be able to access your vars in your scripts by accessing from_server variable from anywhere.
Im pretty much stuck, because i cant figure out how to "call" resource files in .js files. I have a login view, on this view i call MVC render method to generate script tag.
#Scripts.Render("~/Scripts/Login.js")
in my Login.js i have a variable :
var yes = "Resources.Resource.Yes";
which should be tranlated to Yes, or Ja, or anything else depends on which cultureInfo is set. Its pretty straight forward to do if i keep script files inside of my view, because then i just call #Resources.Rescource.Yes and it will work, but if script file is external, then it wouldnt work. How do i solve this?
The answer to this question would be largely opinion-based.
There are three main approaches i encountered working on various projects:
Localization handlers. You define the resources keys in javascript, in $(document).ready() you use ajax to get the localized values from a controller/httphandler dedicated to this and replace keyed text.
In-line js. Basically, you dump external .js and render scripts inside <script> tags in your views/pages.
Global variables. In the view your define global variables, like so:<script language="text/javascript">var myString='<%= Resources.MyString %>';</script>, then use the variable inside included .js.
Personally i prefer approach n 3 -> you can have a single place in code to create all variables and the page loads in one go.
Is there a way to implement if statements inside :javascript filter with HAML in Rails?
I've tried various ways such as
:javascript
$(function(){
- if #booth.greeting_video?
= $('#greeting_video').modal();
But they do not seem to be working at all.
Is there a clean way of implementing this?
The filters in HAML are processed separately from the other code, and the only thing allowed here is the #{} method, which just inserts a Ruby value.
Theoretically you can insert your condition there, and return different values depending on it. And I can't guess what you're trying to do with = $('#greeting_video').modal(); - it looks like javascript, but why is there = sign before, making it look like ruby insertion?
And, it also needs to be said, it's not really a good idea to mix up back-end and fron-end so much. The js variable can be set here, and somewhere in another file the modal would be rendered or not, depending on that variable (just another way suggestion)
I have an array defined in my rails controller:
str_array = ["Hi","hello"]
I need to access this array in my javascript file stored under assets.
I have defined a variable type of array of arrays in my js. I tried accessing like this but failed :
var js_arr = [<%= raw #str_array.to_json %>];
Is there any other way to access the rails array in my javascript?
A very clean way to pass stuff from RoR to JS is the gon gem.
No nasty printing variables with erb or such stuff.
You get an object called gon which you can pile data into in your RoR-controller. Add include_gon to your layout, and voilĂ - the gon object is available in JS too.
Have you added a .erb extension to that JavaScript file?
There are two ways.
1) Pass it up to the javascript via ajax as necessary. (e.g on a Button Click or the like).
2) Put inline javascript in one of your view templates (erb, haml, or w/e) where you want to access it, and then pass the rails array with #{rails_array}.to_json in your method call.
The first is cleaner, more testable, and in the long term more maintainable. The second is easier to implement.
There are essentially 2 places to define JavaScript functions in Grails, directly in a element on the GSP, and within a separate javascript source file under /web-app/js (for example, application.js). We have defined a commonly reused javascript function within application.js, but we also need to be able to generate parts of the function dynamically using groovy code. Unfortunately, ${some groovy code} does not appear to be processed within separate javascript source files.
Is the only way to do this by defining the javascript function within a script tag on a GSP page, or is there a more general solution? Obviously we could define the javascript function in a script tag within a template GSP file which would be reused, but there is a lot of push to keep our javascript functions defined all together in one place (i.e. the external javascript source file). This has performance benefits as well (the javascript source files are usually just downloaded once by each client's browser, instead of reloading the same javascript functions within the source of every html page they visit). I have toyed around with the idea of breaking the function up into static and dynamic pieces, putting the static ones in the external source and putting the dynamic ones in the template GSP, then gluing them together, but this seems like an unnecessary hack.
Any ideas?
(edit: It may sound like the idea of dynamically generating parts of a JavaScript function, which is then downloaded once and used over and over again by the client, would be a bad idea. However, the piece which is "dynamic" only changes perhaps once a week or month, and then only very slightly. Mostly we just want this piece generated off the database, even if only once, instead of hard coded.)
An easy solution to keep your JavaScript unobtrusive is to create a JavaScriptController and map its actions "/js/*" by adding this to your UrlMappings.groovy file:
"/js/$action"{
controller = "javascript"
}
then just create an action for each dynamic JS file you want, include in in your layout <HEAD>, and presto, you've got a JS file that you can insert Grails snippets into! :)
Note: I've found that there's currently a bug in Grails that doesn't map file extensions to content-types properly, so you'll need to include <%# page contentType="text/javascript; UTF-8" %> at the top of your view files.
This is a great solution. I would like to offer a suggestion to use somthing other then a mapping of "/js/$action" because this is no longer going to allow you to access you javascript files in /web-app/js/. All your javascript files would have to be moved to a the directory your controller would point to.
I would use something like
"/dynjs/$action"
This way you still can point to files in the /web-app/js/ files with out conflict and enjoy the benifits of gsp tags in javascript files
Please correct me if I'm wrong.
Or this... have a tag/service/dynamic method that lets tags write out their JS+CSS+whatever else, to a "cache" which is used to build the JS+CSS resources by a different controller.
Full concept here: [http://www.anyware.co.uk/2005/2009/01/19/an-idea-to-give-grails-tags-esp/][1]
If you want to use models created by the controller (that rendered HTML page which reference the Javascript in which you intend to use groovy code) in the Javascript code, then you can use this technique:
This technique does not need to change URL mappings and does not require you to create extra controller.
In your view GSP add javascript as follows:
<script type="text/javascript">
<g:render template="/javascript/yourJavascriptFile"/>
</script>
In views folder create a "javascript" folder. And create a file named:
_yourJavascriptFile.gsp
You can not only use all the GSP code in your _yourJavascriptFile.gsp file, but you can also use all the models created in your controller (that is rendering the view).
NOTE: There is nothing special about javascript folder. You can name it anything you want OR use an existing view folder. This is just a matter of organizing and identifying your HTML spitting GSP from Javascript spitting GSPs. Alternatively, you can use some naming conventions like: _something.js.gsp etc.
Name your scripts like this
/wherever/the/js/files/are/thescript.js.gsp
The gsp code inside will be rendered correctly by grails. This works, but I have no idea if it's considered a Good Idea or not.
There is another way - pass in the generated code into a function that expects closures. Those closures is generated by the program of course. The generated code is of course inlined/script-tagged in the gsp page.
it may or may not work depending on the nature of the code being generated. But i suspect it will work, and if it doesnt, minor tweaking to the coding style of your javascript will definitely make it work. Though, if these 'generated' code doesnt change much, this quite overkill imo.