Passing variables from views.py into script.js

1.4k Views Asked by At

I was wondering whether or not it was possible to pass variables from render_to_response in views.py into script.js,

render_to_response('appname/basic.html',{'var':somevariable})

I basically want to access the variable {{var}} outside of the HTML page since my script.js uses something like:

function WillHappen()
{
    var n = noty({
        text: 'You're {{var}}!',
        type: 'warning',
        dismissQueue: false,
        layout: 'center',
        theme: 'defaultTheme'
    })

}

It works if I put the Javascript into the HTML page but I wanted to separate them since I might be using it in a lot of my HTML pages.

2

There are 2 best solutions below

0
Leandro On

A no good solution is writing your code between <script></script> in a html file

maybe in a my_script.html:

<script>
    function WillHappen()
    {
        var n = noty({
            text: 'You're {{var}}!',
            type: 'warning',
            dismissQueue: false,
            layout: 'center',
            theme: 'defaultTheme'
        })

    }
</script>

But, is this good?

0
bthe0 On

Well, you could have all the variables inside a script tag, and access them through other javascript files such as:

<script>
var test = {{var}} || false;
</script>

And inside other js files:

if (window.test) {
//
}