Can I load template file with dynamic javascript file. For example when I render a.html, I want to load a.js
How can I do this?
If you just want to include a static javascript file, you can do it the same way that you load any other javascript file in HTML:
<script src="jquery-1.11.2.min.js"></script>
However, if what you want to do is pass in a javascript file that the template will load, depending on some backend output, something like this will work:
#views.py
from django.shortcuts import render
from django.template import RequestContext
def my_view(request):
# Logic here...
js_file = "jquery-1.11.2.min.js"
render_to_response('template.html',
context_instance=RequestContext(request,{
"js_file": js_file
}))
#template.html
<script src="{{ js_file }}"></script>
Related
How to use a js file outside Laravel Blade html?
Besides my layouts file, I have a single file welcome.blade.php for the html and it requires a fair amount of scripts. To improve neatness, I wanted to move the <scripts> from the bottom of welcome.blade.php into a separated .js file.
See below for current code, mainly a test to get things working.
welcome.blade.php
#extends('layouts')
#section('content')
<div>
Body Content
</div>
#endsection
// Script added to the bottom of welcome.blade
// How to move into a separated file, like in resources/js/welcome.js
// <script src='/js/welcome.js'></script> doesn't work
<script>
alert('js works');
</script>
Even when I create a new welcome.js script inside the resources/js folder, linking via src or assets doesn't work.
I don't want to put it in the app.js (default laravel install folder structure), because then it'll load in for EVERY page, instead of just welcome.js.
I've tried using stack, but the file doesn't exist when using asset. However, it does work when writing the script itself into the push block. But then that's not using a separate .js file anyway...
layouts.blade.php
<body>
...
#stack('scripts')
</body>
</html>
welcome.blade.php
...
#push('scripts')
// Works when directly writing the script here
// Trying to use `<script src="{{ asset('js/welcome.js' }}"></script>` fails
// No js/welcome.js found.
<script>
alert('js works');
</script>
#endpush
How can I use a separate .js file inside a Laravel Blade HTML Template?
Edit
Did I actually need to make the welcome.js script public in webpack mix? It seems to work now after adding the additional .js line.
See answer.
Versions: Laravel 8
Issue was that the separated .js file didn't exist anywhere, hence couldn't be by welcome.blade.php. Solved by outputting the script to public in webpack mix
Script file, welcome.js
alert('js works');
welcome.blade.php
#push('scripts')
<script src="{{ asset('js/welcome.js' }}"></script>
#endpush
layouts.blade.php
<body>
...
#stack('scripts')
</body>
</html>
webpack.mix.js
mix.js('resources/js/app.js', 'public/js')
.js('resources/js/welcome.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
//
]);
I want to use the package Sortablejs within my blade file.
Thus, I installed it with npm and created a sortable.js file inside my assets with this content
import Sortable from "sortablejs";
which is compiled into the public folder using webpack.mix.js
I expected that I could use it like this within my blade:
<script src="{{ asset('js/sortable.js') }}"></script>
<script type="text/javascript">
var documentlists = $('#documentlist');
Sortable.create(documentlists);
</script>
However, this results in the error:
Uncaught ReferenceError: Sortable is not defined
http://localhost:8004/admin/settings/businessagreement:715
Why can't I include it like this and how would I need to do it?
Your import statement needs to be in the same file as your Sortable code. Then you can run npm run watch to create your script with laravel mix.
Blade file loads Javascript files
<script src="{{ asset('js/sortable.js') }}"></script>
<script src="{{ asset('is/myscript.js') }}"></script>
myscript.js is generated by npm run watch
import Sortable from "sortablejs";
var documentlists = $('#documentlist');
var sortable = Sortable.create(documentlists);
Maybe it even works when leaving out the first script tag.
Ok First In app.js put
import Sortable from "sortablejs";
and make sure that it is imported => if you use vs code press ctrl + click on sortablejs if not just try
npm run watch then in your main blade import app.js
<script src="/js/app.js"></script>
then do whatever you want
I would like to make use of a javascript library (specifically this one) in my Bokeh javascript callback. How can I specify importing of this javascript library such that the library is accessible from Bokeh's js callback functions?
The examples at:
https://docs.bokeh.org/en/latest/docs/user_guide/extensions.html
mainly talk about creating a custom Bokeh Model. I am not particularly interested in creating a new Model, just want to use the library functions in a callback to modify the data that is plotted.
There are two ways:
Server app
Standalone HTML app
Here is how:
Server app:
You can create a Bokeh server directory structure.
create a directory called myapp
name your Python script main.py and put it there
create a subdirectory there called templates
create index.html, main.js and optional styles.css files and put them in templates subdirectory
open terminal, navigate to directory one level higher than myapp directory and start your app with this command: bokeh serve --show myapp
The following example works for Bokeh v1.0.4.
Directory structure:
myapp
|
+---main.py
+---templates
+---index.html
+---main.js
+---styles.css
main.py
from bokeh.plotting import curdoc
from bokeh.models import Button, CustomJS
button = Button(label = 'Click Me')
button.callback = CustomJS(code = """ alert($) """)
curdoc().add_root(button)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<meta charset="utf-8">
{{ bokeh_css }}
{{ bokeh_js }}
<style>
{% include 'styles.css' %}
</style>
</head>
<body>
<script>
{% include 'main.js' %}
</script>
{{ plot_div|indent(8) }}
{{ plot_script|indent(8) }}
</body>
</html>
Please note that this way you can include local, but also remote JS libraries or style sheets.
main.js
$(document).ready(function() {
alert('jQuery succesfully loaded !')
});
styles.css
body { background: #111122; }
> Standalone HTML app:
import os
from bokeh.io import save
from bokeh.models import Slider
from bokeh.util.browser import view
template = """
{% block postamble %}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function() {
var slider = Bokeh.documents[0].get_model_by_name('my_slider')
alert('slider value: ' + slider.value)
});
</script>
{% endblock %} """
slider = Slider(start=0, end=10, value=5, name='my_slider')
save(slider, template=template)
view(os.path.join(os.path.dirname(__file__), os.path.basename(__file__)).replace('.py', ".html")
When the gray div is clicked I want the website to be opened in a new tab, but here this javascript code isn't working. Why? How I can edit it?
views.py:
from django.shortcuts import render
from django.http import HttpResponse
def test(request):
return render(request, 'test.html')
test.html:
<html>
<head>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#gray").click(function(){
window.open("http://www.w3schools.com");
});
});
</script>
</head>
<body>
<div id='gray' style="width:100px;height:100px;background:gray;"></div>
</body>
urls.py:
from django.conf.urls import include, url
from secondv.views import test
urlpatterns = [
url(r'^test', test),
]
The jquery.min.js file is in the template directory, the same directory as test.html file.
Template directory is only for templates. All static content such as js, images should be placed to static directory. It's well described in docs
https://docs.djangoproject.com/en/1.9/intro/tutorial06/
https://docs.djangoproject.com/en/1.9/howto/static-files/deployment/ - for production
In following code snippet I'm trying to add JavaScript Files from Tornado server in HTML file in <HEAD> tag.
DEBUG_SCRIPTS = ''' <script src="src/main.js" type="text/javascript"></script> '''
class Entries(tornado.web.UIModule):
def javascript_files(self):
return 'src/main.js'
class MainHandler(tornado.web.RequestHandler):
def get(self):
params = {}
params['CORE_SCRIPTS'] = DEBUG_SCRIPTS
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.render(path, params=params)
by params['CORE_SCRIPTS'] = DEBUG_SCRIPTS I was trying to add the <script> tag in HTML but it gets parsed in text which generates
<script type="text/javascript" src="src/main.js"></script>
So I came across javascript_files() method in tornado specs but I'm not getting any examples about its implementations. Can anyone help?
javascript files only works with UIModules. Javascript files included that way are appended to the page just before the end of the body tag, though, not in the head tag.
If you really want the file included in the head tag, you can simply output the value of params['CORE_SCRIPTS'] in the head tag of your template:
{% raw params['CORE_SCRIPTS'] %}