1

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.

WToa
  • 290
  • 3
  • 12
  • In that case, how would you suggest I do it? All I want is to display what {{var}} contains in a separate Javascript file which is usually an integer of some sort. – WToa May 14 '13 at 08:04
  • 1
    In your template: `{{ var }}`. Then in your javascript `var text = document.getElementById("myhiddenvar");` – Henrik Andersson May 14 '13 at 08:06
  • 1
    Have a look at the [HTML5 data tag](http://ejohn.org/blog/html-5-data-attributes/), which is nice if you don't want to end up with a lot of ids and classes (mixin style hooks and data identifiers) – Hedde van der Heide May 14 '13 at 08:23
  • @Hedde Yeah, great tip! :) I normally assume that there aren't many who uses HTML5 stuff yet and refrain from using it in answers. – Henrik Andersson May 14 '13 at 08:32
  • You can define a global js variable in your template and acces to it into your your script file. `` and in your script.js `text: "You're "+myVar+" !"` – Mounir May 14 '13 at 10:25

2 Answers2

0

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?

vinay Maneti
  • 1,447
  • 1
  • 23
  • 31
Leandro
  • 2,217
  • 15
  • 18
0

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) {
//
}
bthe0
  • 1,354
  • 2
  • 13
  • 25