Nunovsky
Nunovsky

Reputation: 395

Pass variable to Javascript file

I'm using Django and jqGrids, and I'm trying to automate the grid's contruction process. There is an issue, that I can't figure out the solution.

I've a Javascript file that I include in the header of my html page, grid.locale-en.js, that contains all strings that appear on the jqGrid's boxes.

<script src="{% static 'project/grid.locale-en.js' %}"></script>

I want to pass to this file one Django variable that has the name of the grid.

This way, I can have has mutch grids as I want, and I only need one grid's code. This will serve to change the following fields.

edit: {
        addCaption: "Add Product",
        editCaption: "Edit Product",

Thanks for the help!

Upvotes: 0

Views: 123

Answers (2)

dm03514
dm03514

Reputation: 55972

2 easy ways are:

  1. You could have django render your javascript

  2. you could set a global JS config variable in your django template and then your JS file could look for the variable.

in django template

<script type="text/javascript">
var CONFIG = {};
CONFIG.GRID_NAME = "{{ your name }}";
</script>

THen in your js file

you can check to make sure that CONFIG.GRID_NAME is set and use it appropriately.

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47222

Assuming you have a container div

<div id="jq-grid-container" data-my-column="{{ variable here }}"></div>

Then where you set up your jQGrid, you can just fetch your variable name with

var myColumn = $('#jq-grid-container').data('my-column');

Upvotes: 0

Related Questions