简体   繁体   中英

How to pass javascript variable to a django template tag

I have created a template tag and that will accept 2 arguments, returns a text. Currently, I am not able to pass a javascript variable value to django template tag. can you help me over here?

javascript code with template tag

function formatState (state) {
        if (!state.id) {
            return state.text;
        }
        console.log(state.text);
        var x = "{% get_data state.text 'account' %}";
        var $state = $('<span class="badge">' + x + '</span>');
        return $state;
    }

Template Tag

@register.simple_tag
def get_data(value, module):
    *****
    x = "hello"
    return x

Your Django template is rendered on the server, then sent to the client where you JS is run. You can't access JS variables from the server in your templates because they don't exist there.

If you need to access data from your front end with Django, you can create a view function that will take a POST request and send you data to you server with JS and then return some template that you can add to your page with JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM