Laravel 5 : including javascript files - javascript

First off, I have to precise that I'm quite new to Laravel and that I have a lot to learn.
In one of my controller I need to call a Javascript function. To do so, I simply
echo "<script>triggerPixel();</script>";
I'm just unsure about where to store my Javascript file containing that function.
From what I got for the moment is that I should use elixir to add a file with something like this in the gulpfile.js :
mix.scripts('myscript.js');
Is this the right way to do it or should I simply add a file in resources/assets/javascripts ?
I'm a bit lost and some explanation would be welcome.
Thanks !

Put your actual .js file inside public/js folder
and then, put all your js reference in one file, for example footer.blade.php inside the resources/views folder.
Inside footer.blade.php :
<script src="{{ URL::asset('js/jquery-3.2.1.min.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('js/custom.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('js/app.js') }}"></script>
and then just call the footer inside one of your blade view using: #include ('footer')

Related

How Can I add Custom javascript file in my laravel project?

Can anyone please guide me regarding how can I add custom javascript in Laravel project?
I did google and found some steps but unable to figure out what the error is going on?
Steps I
Created a custom.js in my public folder with a simple function
add script tag in my app.blade.php
extends my layout
But the function is not working
$(document).ready(function()
{
alert("hello this is test");
})
custom.js
enter code here
<script type="text/javascrip" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>"
<script type="text/javascript" src="{{asset('js/custom.js')}}"></script>
code I added in my main file app.blade
but when load my page it doesn't give me an alert. Alert is just for testing I tried with various function.
You misspelled javascript
Remove the (") after writing the </script>
For Javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ URL::asset('js/custom.js') }}"></script>
Make your directory structure is like this for JS: /public/js/custom.js
I have to review your code. I have found an error in your code like a spelling mistake.
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>"
You have miss t at the end of javascript.

Manage static link in js libraries within django

So I was trying to add an audio recording function to my website developed with django.
I wanted to do something similar as https://github.com/addpipe/simple-web-audio-recorder-demo so I started by trying to run it without modification.
I took the same html as in the git linked above, put the js/ folder in my static/ folder, and simply changed the following lines (index.html, line 32-33)
<script src="js/WebAudioRecorder.min.js"></script>
<script src="js/app.js"></script>
for
{% load static %}
<script src={% static "js/WebAudioRecorder.min.js" %}></script>
<script src={% static "js/app.js" %}></script>
These js files load correctly, but the problem is that when I click record on my website, I get a "GET /myapp/record/js/WebAudioRecorderWav.min.js HTTP/1.1" 404 error in my django server.
WebAudioRecorderWav.min.js is called within WebAudioRecorder.min.js. I tried to use the {% load static %} trick in the js file, but it doesn’t work.
What would be the correct way to work around this?
Thanks in advance.
You should use the workerDir setting to set the correct path to the other imported js files. Probably your recorder is initialised in app.js, where you cannot use template tags like {% static %}. The best way is to create a global variable in your template before loading app.js:
In your HTML template:
<script>var jsFilesPath = "{% static 'js/' %}"</script>
<script src="{% static 'js/app.js' %}"></script>
In your app.js:
if (typeof jsFilesPath !== "undefined") {
audioRecorder = new WebAudioRecorder(sourceNode, {
workerDir: jsFilesPath // must end with slash
});
}

How to include simple JavaScript within Hugo

Given the following code:
$('img').mouseenter(function(){
//...
}).mouseleave(function(){
//...
});
I'd like it to be included in my articles. I'd like to avoid editing the theme if possible so to avoid forking etc.
This depends a little on which theme you use. This may be an area where we could do a better job, but do this:
In the theme, look in the
layouts/partials folder.
If you find a header.html or similar, copy this to your local layouts/partials. You can then override the content of this file only. Alternatively you can customize by copying the template used for single pages, often: layouts/_default/single.html.
bep's answer is excellent, but here are some additional details for hugo/frontend newcomers like me
1. Find a place in your HTML where to include the JS
First, one should copy the header.html or footer.html (or similar) of the Hugo theme to your layouts/partials folder. It does not necessarily have to be the header or the footer, but a file that is included in every page on your html (and that's why you would typically use the header.html or footer.html).
I got a theme that had the footer at <theme_folder>\layouts\partials\_shared\footer.html, which I then copied from the theme folder into the project layout folder <project_root>\layouts\partials\_shared\footer.html.
2. Include the script.js in the HTML
Then, I added to the bottom of footer.html
<script defer language="javascript" type="text/javascript" src="{{ "/js/myscripts.js" | urlize | relURL }}"></script>
The defer attribute can improve the page loading time a bit, and "/js/myscripts.js" is the location of my javascripts. The location is path relative to <project_root>\static\. Here are the documentation about relURL and urlize.
The example script file contains just
// myscripts.js
function myFunction(x) {
let d = new Date();
alert("Current datetime: " + d + "\nYou passed in: " + x);
}
3. Use the JS function
This is an example of using the JS function from within Hugo template (any .html belonging to the template):
{{ $somevar := "spam"}}
<button onclick="myFunction( {{ $somevar}} )">Click me</button>
Inline JS
It looks like also inline JS runs just fine; for example, adding
<script>
alert("Script loaded!");
</script>
to a template html file ran just fine. I would use this only for quick testing though, since some scripts might be needed in multiple html files, and adding the same script to multiple files would just increase your overall website filesize.
I copy themes/whatever/layouts/_default/baseof.html to layout/_default/baseof.html and add the following block at the end of the html tag:
{{ block "page-script" . }}{{ end }}
Then I can add
{{- define "page-script" -}}
<script>console.log("Hello!")</script>
{{- end -}}
in my layouts files to put in a script.

Django: How to keep JavaScript code separate in static folder when it uses a python variable

I have a bunch of canvases that needs to be rendered. I don't want put the
JavaScript code in a python loop, because I feel it's bad practice
home.html
{% load staticfiles %}
<head>
<script type="text/javascript" src="{% static
'canvas/canvasrender.js' %}"></script>
</head>
{% for canvas in user_canvas_set %}
<canvas class = "canvas" id="{{canvas.id}}" width="400" height="200"
canvas_post= ""{{canvas.canvas_post}}"" >
Your browser does not support the HTML5 canvas tag.</canvas>
**<script>
canvasrenderNP.canvaswrite("{{canvas.id}}","{{canvas.canvas_post}}")
</script>**
{% endfor %}
I made a custom function that returns an array of the users canvas ids, because I use the canvas id as the id for the canvas element.
home.html
<script>
alert("{{user_canvas_ids}}")
</script>
I get the desired output:
[247, 248, 251, 252]
Now when I put this in a static file
canvasrender.js
alert("{{user_canvas_ids}}")
then load it into
home.html
{% load staticfiles %}
<head>
<script type="text/javascript" src="{% static
'canvas/canvasrender.js' %}"></script>
</head>
output:
"{{user_canvas_ids}}"
I am confused to as what is going on. I thought that the script tag inserts the js file in between the "<script> </script>"
I know I can make a element like so and get the attribute, but I feel like that is not good practice, or is it fine?
<p id="canvas_ids" canvas_ids ="{{user_canvas_ids}}"> </p >
Is there anything else I can do so that I can avoid writing JavaScript code
in the HTML file?
Why this is not a duplicate question. It does not have anything about why the linked js file in the html page can not keep reference to the python variable. But if the JavaScript is coded in the html page it can
As you mentioned in your own comment, you can save user_canvas_id in a js variable in home.html and access it in your js file. Something like this:
<head>
<script>var user_canvas_id = "{{ user_canvas_id }}"</script>
<script type="text/javascript" src="{% static 'canvas/canvasrender.js' %}"></script>
</head>
I am confused to as what is going on. I thought that the script tag inserts the js file in between the "<script> </script>"
Kinda, but this is done client-side, by the browser who has no idea about the special meaning of curly braces in Django templates.
And static in the context of Django means just that: That Django serves that file as-is, without running it through the template engine. (Which wouldn't help here anyway, as for the JavaScript file in isolation, the value of user_canvas_ids would be unknown, so the template engine couldn't substitute anything useful for it.)

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