Laravel does not evaluate the curly brackets when including .js file - javascript

I have a js file with the following script
alert("{{ route('contacts.show',':contactid:') }}");
I used the .js file and include it in my blade view
<script type="text/javascript" src={{ asset('admin/js/contact/test.js') }}></script>
But if I write the script in the blade view. It does evaluate the codes inside the curly brackets.

The JS file is not processed by PHP, so the Laravel blade templates would not be in effect in the JS file. What you should do, is define the route in a variable in JS ON THE PHP PAGE by injecting the route value into a JS variable. Then you can access that variable in your JS file.
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<script>
// Inject the PHP route value into a JS variable.
window.route = '<?php echo route("contacts.show",":contactid:"); ?>';
// You can also use 'let route = ...' to declare the variable.
</script>
<script src="./main.js"></script>
</body>
</html>
main.js:
alert(route);

Curly brackets are executed only when inside a blade file. If you need to keep the JS external and not merge the code into a blade template, you could define a JS variable in blade, in the global JS scope, load the external JS after it and then use that variable in your js.
in blade
<script>
var contactsRoute = ""{{ route('contacts.show',':contactid:') }}"";
</script>
<script type="text/javascript" src={{ asset('admin/js/contact/test.js') }}></script>
In the external js
alert(contactsRoute);

Related

I would like to use a <script> in my Angular component, how do I do that ? (TypeScript, Angular12)

This is the code that I would like to use in my Angular component:
<form action="https://www.meu-site.com/processar-pagamento" method="POST"> <script
src="https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js"
data-public-key="ENV_PUBLIC_KEY"
data-transaction-amount="100.00"></script></form>
If you have to load the script from remote site you can add it to your index.html file, like you would do in a regular html site.
index.html
<!-- get script from 3rd party site -->
<script
src="https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js"
data-public-key="ENV_PUBLIC_KEY"
data-transaction-amount="100.00">
</script>
Then, to use the the script in your component, you need to manually declare the exported variables / functions to avoid TS compilation errors
** formComponent.ts**
declare let web-tokenize-checkout: any; //declare the name of the global object you got from the script you added
//use your script functionality, That part is really depends on how the script you imported works
web-tokenize-checkout.doWhatEverYouNeed(....);

How to access external javascript files through jinja[Flask]?

I wanna know whether i can access external javascript files through jinja?
It's working well with html files or with js embedded in html files but not when javascript file is external.
code:
#app.route('/')
def default():
return render_template('main.html', var1 = 1, var2 = 2)
main.html code:
<html>
<body>
<p>The first value is {{var1}}</p>
<script src="main.js"></script>
</body>
</html>
main.js file:
window.onload=function(){
console.log('{{var2}}');
};
now the jinja code in main.js is not working
Maybe it's not possible to use it in external js?
If someone can help, please reply to this thread.
You need to understand how Jinja works. When you run the commmand
return render_template('main.html', var1 = 1, var2 = 2), it gets processed in the following way:
The Flask server opens the main.html template
Renders/replaces all the defined Jinja variables i.e. the context into the template
Sends the rendered HTML to the client.
Hence the variables are not loaded into the {{ var }} place-holders on the client side but at the server side.
Therefore to achieve what you are trying to do you could do something as follows:
In main.html code:
<html>
<body>
<p>The first value is {{var1}}</p>
<script>var var2 = {{var2}};
<script src="main.js"></script>
</body>
</html>
In main.js code:
window.onload=function(){
console.log(var2);
};
Note: We have added the script inside HTML code before calling main.js which the dependent script.
Let me know if this solves your issue and you have understood the explanation.
TLDR; Pass your flask variable to a global JS variable from your HTML file.
I don't think that it's possible to access external JavaScript files directly from Flask. But you can use this hack, it works with many templating languages (Jinja, EJS...)
main.py:
#app.route('/')
def default():
return render_template('main.html', var1 = 1, var2 = 2)
main.html
<html>
<body>
<p>The first value is {{var1}}</p>
<!-- Insert this <script/> tag before loading you main.js -->
<script type="text/javascript"> window.myVar1 = "{{var1}}" </script>
<script src="main.js"></script>
</body>
</html>
main.js
window.onload=function(){
// Now you can access to myVar1 directly
console.log(myVar1);
};

How to create Backbone View in a separate js file

I'm trying to understand how to modularize the Backbone ToDo tutorial
Originally everything is inside the same file, but if I try to extract to another file:
var TodoView = Backbone.View.extend({
...
});
then this throws an error:
var view = new TodoView({model: todo});
**Uncaught TypeError: undefined is not a function**
It's probably due to a scope issue, but I don't know how to create a reference inside the $(function() so I can create this new object inside the main function.
Assuming that your first code part is TodoView.js,
and your second code part is app.js.
Write your html file like this,
<html>
<head>
<script type="text/javascript" src="js/TodoView.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
// your dom
</body>
</html>
(Edited, at 2015-07-27)
sorry for my late reply.
how about this?
<html>
<head></head>
<body>
<!-- your dom -->
<script type="text/javascript" src="js/TodoView.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
In many case, most javascript codes are appended to just before </body>, so that javascript can use your dom!
You can use something like require.js to load your external files and manage dependancies.
Ok, the solution was to move the script references to the end of the body instead of inside the head tags.
I think that the reason is that TodoView.js is making use of templates that were defined in the body, and since the js file was being loaded before the body, the templates were not yet available.

Why I can't type any letter if I separate the .js file?

Actually I was trying to get the concept of the module pattern. Here I have simple code which I used to type directly on the page. It was fine until I tried to separate the actual code from the HTML file and kept only a single line of code on the main HTML file:
<body>
<script type='text/javascript' src='module.js'>
// module.JS file was here ....
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>
</body>
File module.JS
var module = (function() {
return {
show:function(keyCode){
document.body.innerHTML+=(String.fromCharCode(keyCode));
}
};
})();
You'll need to have two <script> elements for this.
Use one to "import" your external module and another for the script you want to embed directly on the page:
<script type='text/javascript' src='module.js'></script>
<script type='text/javascript'>
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>
For more information, you can check out this MDN documentation page. Here is an excerpt talking about the src attribute (emphasis added):
This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. Script elements with an src attribute specified should not have a script embedded within its tags.
A script block referring to an external JavaScript source should be separate and any script inside of it does not get executed. So you need two separate script blocks one for the external JavaScript file and the other for your script.
<script src='module.js'></script>
<script>
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>

How to call a Python function from an external JS file?

I was using some Javascript stuff for an uploader on a webpage, to test it I wrote it inline with the HTML (I know). I'm using Flask with Jinja2 templates so to connect my uploader(it just acts like a form) to the upload function in my Python, I just had
url: "{{url_for('upload_file')}}",
in the inline Javascript, because this could be referenced within the scope of the template. Now I've moved my JS to an external file and just included it in the HTML like so:
<script type="text/javascript" src="{{ url_for('static', filename='uploader.js') }}">
</script>
How can I call my Python function from the external js file? Is there some way of initializing it in the template and passing it in, or am I missing something really elementary here?
Edit: I ended up doing it a little different:
<script>
var link = "{{ url_for('upload_file') }}"
</script>
<script type="text/javascript" src="{{ url_for('static', filename='uploader.js') }}">
</script>
As you say, you need to do this in the main file. Inside a script tag, you can define an object in the global scope, and set attributes to the results of your template calls. You can then refer to the object in your script file.
Edit
There's no special syntax: this is just standard Javascript.
<script type="text/javascript">
template_vars = {
url: "{{url_for('upload_file')}}",
// etc
}
</script>
and now your other script can access template_vars.url etc.

Categories

Resources