I intigrate Stripe Api for testing how can i set public key in env.
How to use in strip public key in js
Public key:
STRIPE_KEY=pk_test_IS796OfBm2ZFLfvBbwsXHJLK00fE6oqivk
and js file where use this veriable:
var stripe = Stripe({{ env('STRIPE_KEY') }});
{{ }} is a .blade syntax control, and cannot be used in .js files.
If you have a <script> element inside a .blade.php file, then it will work, but otherwise you'll need to load the file into JS before including the .js file, or get the value via an ajax call.
For example, loading the variable to js before including the .js script:
example.blade.php:
<script type="text/javascript">
let stripe_key = '{{ env("STRIPE_KEY") }}';
</script>
<script src="{{ asset('js/stripe.js') }}"></script>
Related
I've a function in views.py which returns latitude and longitude:
return render(request, 'map.html', {'lat_lng':lat_lng})
and I am able to access it in html file as {{ lat_lng }} but when I try to use lat_lng in separate js file then I'm not able to access it.
I tried all below stack answers but none worked for me:
Django Template Variables and Javascript
Passing django variables to javascript
How to use Django variable in JavaScript file?
Passing Python Data to JavaScript via Django
You can take advantage of json_script template tag. In your template do this
{{ lat_lng|json_script:"lat_lng" }}
Then in your javascript file you can access this variable like
const lat_lng = JSON.parse(document.getElementById("lat_lng").textContent);
One simple way to do it is to append the following snippet at the top of your template html file(the one that imports your javascript file):
<script type="text/javascript">
const LAT_LNG = "{{ lat_lng }}"; // Or pass it through a function
</script>
when I try to use lat_lng in separate js file then I'm not able to access it.
You can't use a django template variable in a static file. The static files will be returned in a way that bypasses Django's typical request processing.
Instead, set the variables on data-* attributes on an known HTML element, then get the element, access the attribute and use the value that way.
Be sure when that getting the variable in a script tag is before including the separate js file
Exmple :
<script type="text/javascript">
var variable = "{{myV}}";
</script>
<script type="text/javascript" src="myJsFile.js"></script>
Until now I have been including scripts in my templates by using {% load static %} and having the javascript code in the static directory, separated from html files, because I thought it was the best practice.
But more and more I need to use context variables in the javascript. Since template tags cannot be integrated directly in the individual javascript static files (as far as I know), I have been importing these values in the javascript from the rendered template by using selectors. For example:
<!--template.html-->
<div id="url_ajax" style="display:none">{% url
"images:products" %}</div>
{%load static%}
<script src="{% static "js/ajax.js" %}"></script>
/*Ajax.js*/
url_ajax = document.getElementById("url_ajax").innerHTML
$.post(url_ajax, {
rankit: this.rankit,
pd: JSON.stringify(pd)
},
function(data) {
if (data['status'] == 'ok') {
[...]
}
}
);
Although this works, I am feeling this is not a good practice due to security reasons or scalability. But I do not know another way of integrating context variables in the javascript rather than integrating javascript code directly in the template, which is neither a good approach if that code will be used in many templates.
As a Django learner I would like to know which is the most often used approach in these situations: separated javascript files which takes context variables from the rendered template, javascript code inserted directly in the template html, or a third approach which I donĀ“t know?
I don't really like your solution, there's no need to create an extra html element to pass the django variable and read it from JS. This is error prone and adds non-needed html elements to your DOM.
Instead I recommend two solutions:
Solution 1
Use a JS script in your template where you'll dump your JS variables and then use them directly from your JS files. To do that, I'll usually have a script inside my template before my custom JS code where I define a global JS object containing all Django variables, like this:
<script>
var g_django = {
url1: '{% url "the_first_url" %}',
url2: '{% url "the_second_url" %}',
image: '{% static "images/an_image" %}'
}
</script>
<script src='{% static "js/ajax.js" %}'></script>
Now I can use g_django.url1, g_django.image etc from inside the js/ajax.js script. This can be used if you don't have many things you need to share between django and JS.
Solution 2
If you have more things you need to share between Django and js and you want to have better control you can create a JS-Django template i.e create a normal JS file inside your templates folder. This file can then either be included inside a <script> tag (check my answer here for a similar solution with css: Django Use Static files URL in Static Files) or, even better be used as a normal django view through a TemplateView. Thus, you'll create a file named django_data.js in your templates folder in which you'll write JS code mixed with django variables for example it's contents may be something like this
var g_django = {
url1: '{% url "the_first_url" %}',
url2: '{% url "the_second_url" %}',
image: '{% static "images/an_image" %}'
}
This file will then need to be included to your urls.py through a TemplateView something like this:
class django.views.generic.base.TemplateView
urlpatterns = [
path('django_data_js/', TemplateView.as_view(template='django_data.js', content_type='application/javascript'), name='django_data_js' ),
]
Now you can visit django_data_js/ to take a look at your JS variables and be sure that everything renders correctly and of course you can include it (as a template) to your scripts like this:
<script src='{% url "django_data_js" %}'></script>
<script src='{% static "js/ajax.js" %}'></script>
Notice the difference between including the template-js (using url) and including the normal static file (using static). You'll then be able to use g_django from inside your js/ajax.js.
I have a javascript static file within which I would like to specify a source url to a non-static json file. The below doesn't seem to work (the root directory here is the root directory of the django project):
source: {url: "users/username1/nonstatic.json"}
It works if I explicitly (and non-ideally) specify an absolute static json url:
source: {url: "static/default_GCMS.json"}
Am wondering what's the correct way of calling a non-static file from a static one (.js in this case).
So you want to call a django view from a static JS file. This is a rather common problem - to solve it you need to mix and match django template logic with static JS.
One easy solution would be to assign the URL of the view you'd like to call to a global JS variable in your django template before including your static JS file and then use that variable. So, your django template would be something like this
<script>
var g_djangoViewUrl = '{% url "my_django_view_url %}';
// Notice that g_djangoViewUrl is global (assigned to your window object) so will be visible from other JS files
</script>
<script src='the_js_file_that_will_use_the_url.js'></script>
The above has the problem that you'll need to remember to define the urls that will be needed before including your js files. A more structured and permanent solution would be to create a django-view whose only purpose would be to output a global object that would contain all the urls you are going to use from other JS files. So, you'll have something like this in your template
<script src='{% url "my_url_creating_view" %}'></script>
<script src='the_js_file_that_will_use_the_url.js'></script>
The my_url_creating_view should have a correct content type (application/javascript) and should just return a object like this:
var g_URLS = {
djangoView1: {% url "django_view_1" %},
djangoView2: {% url "django_view_2" %}
}
etc
I'm trying to send a variable (user.id - current user's id) into my JQuery file which calls a view to delete some data in a database. The problem is that I don't know how to pass user.id into the JS file to be able to append it to url request.
In my template:
<script src="{% static "js/checkTestsSittings.js" %}">var userid = {{ user.id | safe }};</script>
JS file:
$(document).ready(function () {
alert(userid); // just a test
request_url = '/check-sittings/'+userid+'/';
$.ajax({
url: request_url
})
});
This is what I see in the console:
I'm beginner in JS and Django. Could you give me a hint?
You can't add file and code in a single script tag, you should add them independently, like this
<script>var userid = {{ user.id | safe }};</script>
<script src="{% static "js/checkTestsSittings.js" %}"></script>
the following JavaScript is working perfect in side the test.blad.php file
but when i made external test.js file at the browser i get some thing like
http://localhost:8000/%7B%7Burl('/barcode')%7D%7D?j_barcode=112234
instead of
http://localhost:8000/barcode?j_barcode=112234
the code in test.js file is :
$(document).ready(function(){
$('#barcode').keyup(function(event){
if(event.keyCode == 13){
var j_barcode = $('#barcode').val();
$.get("{{url('/barcode')}}", {j_barcode:j_barcode}, function(data) {
console.log(data) ;
//success data
$.each(data,function(i, obj){
document.getElementById("item").value =obj.itemName;
document.getElementById("itemId").value = obj.id;
console.log(data) ;
});
});
}
});
});
and the route.php
Route::get('/barcode' , 'testController#getBarcode');
at last i decleared the test.js in test.blade.php as
<script type="text/javascript" src="/hsm/js/test.js" ></script>
You can not use blade or php code inside files which are not interpreted by php.
The simplest way, as already suggested by #dev-null is to hardcode that url. But that generates problems when you're on a sub page like "/articles/2015" since it will then try to call "/articles/barcode".
You will have to find a way to pass the site root url to your js file.
The way I always solve this is to define a global variable in my main template with all the php interpreted values required in js.
var App = {
root: '{{ url('/barcode') }}',
texts: {
// some translated texts for js
}
};
That way you can easily access it in all your js files:
$.get(App.root + '/barcode')...
Note: If you use named routes like me you will have to add each URL separately instead of just the root.
After some research, this is my solution:
Step 1. In the blade file, add a yielded section, immediately (just to keep your scripts neat) before referring to external .js file, do something like following,
#section('js_after')
<script>let dataUrl = "{{ route('subcat') }}"</script>
<!--Then external javascript file -->
<script src="{{ asset('js/pages/somescript.js ') }}"></script>
#endsection
Step 2. In your somescript.js file, you may refer and manipulate with this pre-defined variable dataUrl, such as,
var url = dataUrl+'?someParam='+id
$.get(url)
reference: https://stackoverflow.com/a/59994382/3107052