Playframework: Elegant way to pass values to javascript - javascript

Does anyone have an elegant solution to pass server values to javascript (that is not inline) in playframework? just like ${x} or &{'x'} inside html
Currently I can think of
<script type="text/javascript">
var x= ${x};
</script>
<script src="/public/javascripts/jsThatUsesX.js" type="text/javascript" ></script>
I'm thinking there is a better solution from play

It's not pretty, but that's the way I always end up doing it.
If the values that you're passing to JavaScript describe something in the DOM, you might consider using HTML 5 data attributes to place that information in the HTML. Then you can retrieve it with getAttribute. e.g. If your page is a blog post and you need to store the post ID you could use
<div class="post" data-post-id="77">
...
</div>
That way the data is separated out from the logic and you don't need to inline any JavaScript. You could also use a hidden form field.

What's wrong with that? I found myself doing things like
<script>
var trades = [${_trades.collect {models.Trade t -> t.price}.join(", ")}];
// ...
</script>
I like it the groovy way ;)

Related

Embed same web widget multiple times with different data attribute values

I want to create a web widget that can be embedded multiple times on the same page but with different data attribute values so I can display different data according to the data attribute value.
For example, I want to embed mywidget.js file multiple times as follows:
<body>
<div>
<script src="script/mywidget.js" data-sport="soccer" id="widget-soccer">
</script>
</div>
<div>
<script src="script/mywidget.js" data-sport="tennis" id="widget-tennis">
</script>
</div>
</body>
My question is, inside the code in mywidget.js, how do I determine the correct script tag reference and read it's data attribute so I can use that value to fetch the corresponding data from a web service. I am using only jquery and javascript.
I want the widget to be embeddable on other users sites as well so all they do is embed using only the script tag and passing in the desired data attribute value without adding anything extra anywhere they need on their website.
This is not really a very good approach, as it is very inflexible. But given that <script> tags, when not deferred, halt parsing of the document while they execute, the current script tag will be the last in the DOM; so you can get the current sport inside your script by using this:
var sport = $('script').last().data('sport');
However, it would be much better to define a function in your external JavaScript file, and then invoke it when you need to instantiate your widget (EDIT: like in Lee Taylor's answer).
Why don't you do something like:
<head>
<script src="script/mywidget.js"></script>
</head>
<body>
<div><script>createMyWidget({sport : "soccer"} );</div>
<div><script>createMyWidget({sport : "tennis"} );</div>
</body>
I don't think you can. I know it's not that nice, but I would try:
<div><script>sport = "soccer";</script><script src="script/mywidget.js" id="widget-soccer"></script></div>
<div><script>sport = "tennis";</script><script src="script/mywidget.js" id="widget-tennis"></script></div>
and use sport in mywidget.js
Another approach could be that myscript.js is actually a dynamic "page", let's say with php, then you could use src="script/mywidget.js?sport=swimming", and in the php you would print:
sport = "<?php echo addcslashes($_GET['sport'], '"'); ?>";
But even better would be:
<script src="script/mywidget.js"></script>
<div><script>showWidget("soccer");</script></div>
<div><script>showWidget("basketball");</script></div>
I think you can use jQuery to find all script tags with src="script/mywidget.js" or something
$('script[src="script/mywidget.js"]')
And then you'll have an array of scripts tags that you can loop through and access the data property using jQuery's .data() method.

Interpret variable in Javascript file Laravel

I need to include a js file in my views.
But in this js file i need to interpret somes PHP variable.
Actually i do this :
#section('javascript')
<script>
alert("{{{test}}}");
</script>
#stop
But i REALLY need to do this :
#section('javascript')
{!! Html::script('js/test.js') !!}
#stop
test.js :
alert("{{{test}}}");
I need to declare a lot o variable. So my JS file will be very huge. And i don't want to show this directly in the source code.
How can i do ?
Thank you !
You can only pass the variable to the javascript like so:
#section('javascript')
<script>
var test = {{{$test}}};
</script>
#stop
then in your javascript file included at the bottom you can use it:
alert(test);
Let me just mention that this is not a great way of handling the passing variables from php to javascript.
When I need to do something like this, I usually create a meta tag on the page which would contain the alert information.
<meta name="someAlertValue" content="{{{ $test }}}" />
Then you can very easily grab that via jQuery.
var alert_text = $('meta[name=someAlertValue]').attr('content');
I find this approach to be much cleaner and maintainable than trying to drop php variables directly into your javascript.
I had the same problem, and wanted to have a stand alone js which will have bunch of variables taken from config() or even from database, multi-language, and will be configurable, or even will work with query parameters.
Maybe it's a hard way, but i've created a route:
Route::get('/js-modules/test.js',function(){ return view('js-modules.test');})->name('my_js);
So in the view resources/views/js-modules/test.blade.php you can put your js code together with your PHP stuff.
Or you can route it to a controller and have even more background work. it looks a bit slow (in the browser) on the first run , but second request it'll be cashed and retrieved as the regular js file
And now you can link it to any of your pages with
<script src="{{route('my_js')}}"></script>

Alfresco- Pass variable values from js controller to freemarker

can anybody tell me what am I doing wrong?
I want to retrieve all my alfresco sites with this code (this should work):
model.sites = siteService.listSites(null, null, 0); // return type= List<Site>
And now i want to retrieve this list model.sites in my HTML freemarker template like this:
<body> ${sites} </body>
How can I view this sites list. I know i am getting it wrong in my ftl, but can't find a solution how to retrieve it.
You'll need to loop over the sites in your freemarker. Assuming you wanted a list of the site names, with commas between them, then your freemarker would instead want to look something like:
<body>
<#list sites as site>
${site.shortName}<#if site_has_next>,</#if>
</#list>
</body>

Javascript inline output

In javascript suppose you have this piece of code:
<div>
<script type="text/javascript">var output = 'abcdefg';</script>
</div>
Is there any way to simply "echo" (using PHP terminology) the contents of output into #test? That is, to output a string inline, assuming you have no standard way of traversing or selecting from the DOM?
document.write("..."); does write the contents of output, but in doing so, it replaces the entire document with the output.
The solution I'm looking for should act the same way a PHP echo would: write the output into the document inline.
You'd have to use document.write [docs]:
<div id="test">
<script type="text/javascript">document.write('abcdefg');</script>
</div>
DEMO
With the caveat that it does not work in XHTML documents. See the documentation for more details.
"Kosher" code aside, yes.
document.write()
In standards-based browsers:
document.getElementByID("test").textContent = output;
For broader support, you could use text in jQuery (or the equivalent method if your library of choice):
$('#test').text(output);
If your code is in the div, then document.write('abcdefg') is the proper choice for inserting something inline at the point of execution.
Or, if your code is not inside the div, you can do this:
<div id="test">
</div>
<script type="text/javascript">
var output = 'abcdefg';
document.getElementById("test").innerHTML = output;
</script>
You will have to make sure that your code runs AFTER the page is loaded and the div is present.
You could write something like:
<div id="test">
<script>
document.getElementById('test').innerHTML = "stuff";
//this line only changes content in the div with id="test", not the whole dom
</script>
</div>
But you should avoid putting a script inside a div because it may be overwritten.
I know this is an old question but if anybody is still looking then here is a handy function that does the job.
function echo(text)
{
document.body.appendChild(document.createElement("div")).appendChild(document.createTextNode(text));
}
console.log()
http://getfirebug.com/logging
also supported in chrome and ie 9.. watch out for backwards compatibly it will get you ie8 and down i think...

How do I use Javascript in my Coldfusion page?

I have a coldfusion page and I am very newbie in coldfusion. What I need to do is to insert the alert in between to see what is the time. In php I could close the php tags and enter the javascript tag and alert out the value. How would I do that in coldfusion? I have this
<cfset right_now=Now()>
<cfscript>
alert(#right_now#);
</cfscript>
But its not working.
thanks
<cfscript> is a Coldfusion tag for using the Coldfusion scripting language (aka CFScript). If you want to use Javascript, open a <script> tag like you would normally in HTML. You'll probably want to make sure it's inside a <cfoutput> tag if you want to use Coldfusion values within your javascript.
<cfset right_now = Now()>
<cfoutput>
<script type="text/javascript">
alert('#right_now#'); // don't forget you need to put quotes around strings in JS
</script>
</cfoutput>
You don't need to even use cfscript for this specific need. You could, for instance, do this:
<script type="text/javascript">
var currtime = new Date();
alert(currtime);
</script>
... Also a point to remember, you can't directly output HTML from within a <cfscript> tag. You can however get around this by calling a function from within a <cfscript> tag that can output the data for you.
Always remember the coldfusion begins and ends before anything else is executed: html, javaScript, sql, etc., so the javascript is getting an already formed code, which is CF instead of being hard coded.

Categories

Resources