Access Twig Variable in OctoberCMS Javascript file - javascript

I am Using OctoberCMS which is based in Laravel Framework and I set variable in my html file
{% set name = 'Juan' %}
and i am trying to access it in my Javascript file by setting variable like this
var myName = '{{ name }}'
and i alert the variable myName but unfortunately it doesn't display the variable myName instead it displayed the whole string like this {{ name }}

The problem is you are defining whole thing in javascript
So, template engine has no clue what you want, what I suggest is just define variables in Html like this
so previously you did this.
{% set name = 'Juan' %}
so now to pass this variable to js you can do something like this for simplicity. [its unprofessional and I do not suggest it instead we can use our namespace/object and pass it]
<script>var myName = '{{ name }}';</script>
make sure this line is not written in js file it must be in one of .htm layout/template or in markup section.
then throughout in your project inside js you can access it.
alert(myName);
and if it do not seems relevant to you then we suggest you to post laravel code which can do stuff like this so we give better working relevant solution.
if you find any doubts please comment.

well javascript file does not support twig templating engine so it will not understand
what is {{ name }} variable.
but you can do a workaround over here like that
in your .htm twig file you can print the variable in a span and make it display:none
<span id="name" style="display: none;">{{ name }}</span>
and then call it into your js file like this
var name = document.getElementById("name").innerHTML
or if you jave jquery included then you can do like this
var name = $("#name").val()
I hope this help

Related

Django: How to pass python variable value to javascript file?

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>

How to Access Context Variables Sent from Django Application in Javascript

I have sent a variable in context from my django python code as so:
context = {
"data": data,
}
return render(request, "template.html", context)
but do not know how to access it in my javascript file. I have tried accessing it like this:
data_from_django = {{ data }}
However this simply gives me a syntax error. Please can someone tell me the correct way to access this variable.
IN Javascript you have to use the variables within the quotes.
data_from_django = '{{ data }}'
if "data" is a JSON value, be sure to use {{ data | safe }}
In the case where variable and javascript code is not in the same html file,the above method will fail.
In the case of separate js file, wrap the variable with a id and later refer to it in the js file:
//template.html
<div id="data_from_django">{{ data }}</div>
//sample.js
var data_from_django =
document.getElementById("data_from_django").innerHTML;

Unable to pass jinja2 variables into javascript snippet

How do i pass jinja2 data into javascript.
I have a Flask REST url as /logs/<test_case_name>
I am trying use .getJSON() to query the above URL and hence would want to pass the jinja2 data which has the testcasename to .getJSON function.
sample code:
<script type="text/javascript">
alert({{name}});
</script>
It doesn't work.
Any suggestions please?
Try with quotes:
alert("{{name}}");
other than encapsulating the variable in a string, an alternate is jquery for profit:
its generally a bad idea to mix template language with javascript. An alternative would be to use html as a proxy - store the name in an element like so
<meta id="my-data" data-name="{{name}}" data-other="{{other}}">
then in the javascript do
var djangoData = $('#my-data').data();
this has advantage in:
javascript no longer tied to the .html page
jquery coerces data implicitly
I know this is a kinda old topic, but since it attracts a lot of views I suppose some people are still looking for an answer.
Here's the simplest way to do it:
var name = {{name|tojson}};
It will 'parse' whatever 'name' is and display it correctly:
https://sopython.com/canon/93/render-string-in-jinja-to-javascript-variable/
This is how I did it
My html Element
<!--Proxy Tag for playlist data-->
<meta id="my_playlist_data" data-playlist="{{ playlist }}">
My script element
// use Jquery to get data from proxy Html element
var playlist_data = $('#my_playlist_data').data("playlist");
See .data() documenttation for more
I just figure I would add the solution I ended up using.
It has a few advantages over the other answers:
It is 100% valid javascript at the template level (no editor/lint errors).
Does not need any special HTML tag.
No dependencies (jquery, or otherwise).
let data = JSON.parse('{{ data | tojson }}');
you can try alert({{name|safe}});
<input type="hidden" name="token_idx" id="token_idx" value='{{token|safe }}'
let token_data = document.getElementById("token_idx").value;

Access MyBB PHP variable with Javascript

Is it possible to grab a MyBB PHP variable with Javascript? I am an userscript coder, and right now I use:
var uid = $("#panel").find('a').attr('href').replace(/[^0-9]/g, '');
To grab the user id (uid) of the current user. However, if I were to grab the UID from the user with PHP, it would look like this:
<?php echo {$mybb->user['uid']} ?>
Now to the actual question. Is it possible to grab the UID through Javascript, using the $mybb->user['uid']?
My answer is Yes, you can but it has some limits.
Well, if you remember in every headerinclude templates always have these code:
<script type="text/javascript">
<!--
var cookieDomain = "{$mybb->settings['cookiedomain']}";
var cookiePath = "{$mybb->settings['cookiepath']}";
var cookiePrefix = "{$mybb->settings['cookieprefix']}";
var deleteevent_confirm = "{$lang->deleteevent_confirm}";
var removeattach_confirm = "{$lang->removeattach_confirm}";
var loading_text = '{$lang->ajax_loading}';
var saving_changes = '{$lang->saving_changes}';
var use_xmlhttprequest = "{$mybb->settings['use_xmlhttprequest']}";
var my_post_key = "{$mybb->post_code}";
var imagepath = "{$theme['imgdir']}";
// -->
</script>
You can use MyBB's variables in any template with one condition: it's must be defined in the correlative PHP file. (Of course that variable must be inside the brackets { })
For example, the correlative PHP file with headerinclude template is global.php.
That's it. Have fun with MyBB :)
You can add a plugin to your forum. It is called template conditionals. Once you have that installed you can use the Mybb->user variable in all templates. There are many applications of this plugin, but for your code you can do:
<setvar uservar>$mybb->user['uid']</setvar>
var {$tplvars['uservar']} = $("#panel").find('a').attr('href').replace(/[^0-9]/g, '');
The plugin is on the MyBBHacks forum at the link below.
http://mybbhacks.zingaburga.com/showthread.php?tid=464
First, you will not be able to directly access a php server side variable in javascript, but there are several work arounds you could do.
The first one that comes to mind is to put this in your html page somewhere
<script type="text/javascript">
<?php echo "var uid = '". $mybb->user['uid']."';" ?>;
</script>
The downside to this is that this variable is now directly view able and editable in the DOM.
If you are using (or can use) a template you may place a PHP variable in a JavaScript variable defined within that template's content. If you plan to run this JavaScript on every page you must add the variable definition to the script block in the headerinclude template.
<script type="text/javascript">
<!--
var userID = {$mybb->user['uid']};
// -->
</script>
That example script will place the user's uid in the JavaScript variable userID.
Please note that <?php echo $mybb->user['uid']; ?> will not work as MyBB's template system does not allow PHP tags within it. You may instead use {$mybb->user['uid'} as an alternative.
Also, take note that if you are using a plugin and eval'ing the template in a function in your plugin file you will also need to globalise the PHP variable you are going to use.

Django Template Variables and Javascript

When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}.
Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.
The {{variable}} is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.
Having said that, you can put this kind of substitution into your JavaScript.
<script type="text/javascript">
var a = "{{someDjangoVariable}}";
</script>
This gives you "dynamic" javascript.
CAUTION Check ticket #17419 for discussion on adding similar tag into Django core and possible XSS vulnerabilities introduced by using this template tag with user generated data. Comment from amacneil discusses most of the concerns raised in the ticket.
I think the most flexible and handy way of doing this is to define a template filter for variables you want to use in JS code. This allows you to ensure, that your data is properly escaped and you can use it with complex data structures, such as dict and list. That's why I write this answer despite there is an accepted answer with a lot of upvotes.
Here is an example of template filter:
// myapp/templatetags/js.py
from django.utils.safestring import mark_safe
from django.template import Library
import json
register = Library()
#register.filter(is_safe=True)
def js(obj):
return mark_safe(json.dumps(obj))
This template filters converts variable to JSON string. You can use it like so:
// myapp/templates/example.html
{% load js %}
<script type="text/javascript">
var someVar = {{ some_var | js }};
</script>
A solution that worked for me is using the hidden input field in the template
<input type="hidden" id="myVar" name="variable" value="{{ variable }}">
Then getting the value in javascript this way,
var myVar = document.getElementById("myVar").value;
As of Django 2.1, a new built in template tag has been introduced specifically for this use case: json_script.
https://docs.djangoproject.com/en/stable/ref/templates/builtins/#json-script
The new tag will safely serialize template values and protects against XSS.
Django docs excerpt:
Safely outputs a Python object as JSON, wrapped in a tag,
ready for use with JavaScript.
There is a nice easy way implemented from Django 2.1+ using a built in template tag json_script. A quick example would be:
Declare your variable in your template:
{{ variable|json_script:'name' }}
And then call the variable in your <script> Javascript:
var js_variable = JSON.parse(document.getElementById('name').textContent);
It is possible that for more complex variables like 'User' you may get an error like "Object of type User is not JSON serializable" using Django's built in serializer. In this case you could make use of the Django Rest Framework to allow for more complex variables.
new docs says use {{ mydata|json_script:"mydata" }} to prevent code injection.
a good exmple is given here:
{{ mydata|json_script:"mydata" }}
<script>
const mydata = JSON.parse(document.getElementById('mydata').textContent);
</script>
For a JavaScript object stored in a Django field as text, which needs to again become a JavaScript object dynamically inserted into on-page script, you need to use both escapejs and JSON.parse():
var CropOpts = JSON.parse("{{ profile.last_crop_coords|escapejs }}");
Django's escapejs handles the quoting properly, and JSON.parse() converts the string back into a JS object.
Here is what I'm doing very easily:
I modified my base.html file for my template and put that at the bottom:
{% if DJdata %}
<script type="text/javascript">
(function () {window.DJdata = {{DJdata|safe}};})();
</script>
{% endif %}
then when I want to use a variable in the javascript files, I create a DJdata dictionary and I add it to the context by a json : context['DJdata'] = json.dumps(DJdata)
Hope it helps!
For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.
Note, that if you want to pass a variable to an external .js script then you need to precede your script tag with another script tag that declares a global variable.
<script type="text/javascript">
var myVar = "{{ myVar }}"
</script>
<script type="text/javascript" src="{% static "scripts/my_script.js" %}"></script>
data is defined in the view as usual in the get_context_data
def get_context_data(self, *args, **kwargs):
context['myVar'] = True
return context
I was facing simillar issue and answer suggested by S.Lott worked for me.
<script type="text/javascript">
var a = "{{someDjangoVariable}}"
</script>
However I would like to point out major implementation limitation here.
If you are planning to put your javascript code in different file and include that file in your template. This won't work.
This works only when you main template and javascript code is in same file.
Probably django team can address this limitation.
I've been struggling with this too. On the surface it seems that the above solutions should work. However, the django architecture requires that each html file has its own rendered variables (that is, {{contact}} is rendered to contact.html, while {{posts}} goes to e.g. index.html and so on). On the other hand, <script> tags appear after the {%endblock%} in base.html from which contact.html and index.html inherit. This basically means that any solution including
<script type="text/javascript">
var myVar = "{{ myVar }}"
</script>
is bound to fail, because the variable and the script cannot co-exist in the same file.
The simple solution I eventually came up with, and worked for me, was to simply wrap the variable with a tag with id and later refer to it in the js file, like so:
// index.html
<div id="myvar">{{ myVar }}</div>
and then:
// somecode.js
var someVar = document.getElementById("myvar").innerHTML;
and just include <script src="static/js/somecode.js"></script> in base.html as usual.
Of course this is only about getting the content. Regarding security, just follow the other answers.
I have found we can pass Django variables to javascript functions like this:-
<button type="button" onclick="myJavascriptFunction('{{ my_django_variable }}')"></button>
<script>
myJavascriptFunction(djangoVariable){
alert(djangoVariable);
}
</script>
I use this way in Django 2.1 and work for me and this way is secure (reference):
Django side:
def age(request):
mydata = {'age':12}
return render(request, 'test.html', context={"mydata_json": json.dumps(mydata)})
Html side:
<script type='text/javascript'>
const mydata = {{ mydata_json|safe }};
console.log(mydata)
</script>
you can assemble the entire script where your array variable is declared in a string, as follows,
views.py
aaa = [41, 56, 25, 48, 72, 34, 12]
prueba = "<script>var data2 =["
for a in aaa:
aa = str(a)
prueba = prueba + "'" + aa + "',"
prueba = prueba + "];</script>"
that will generate a string as follows
prueba = "<script>var data2 =['41','56','25','48','72','34','12'];</script>"
after having this string, you must send it to the template
views.py
return render(request, 'example.html', {"prueba": prueba})
in the template you receive it and interpret it in a literary way as htm code, just before the javascript code where you need it, for example
template
{{ prueba|safe }}
and below that is the rest of your code, keep in mind that the variable to use in the example is data2
<script>
console.log(data2);
</script>
that way you will keep the type of data, which in this case is an arrangement
There are two things that worked for me inside Javascript:
'{{context_variable|escapejs }}'
and other:
In views.py
from json import dumps as jdumps
def func(request):
context={'message': jdumps('hello there')}
return render(request,'index.html',context)
and in the html:
{{ message|safe }}
There are various answers pointing to json_script. Contrary to what one might think, that's not a one size fits all solution.
For example, when we want to pass to JavaScript dynamic variables generated inside a for loop, it's best to use something like data-attributes.
See it in more detail here.
If you want to send variable directly to a function by passing it as a parameter then try this
<input type="text" onkeyup="somefunction('{{ YOUR_VARIABLE }}')">
As from previous answers the security can be improved upon

Categories

Resources