[Answer]-How to pass raw strings or integers into django template filters?

1👍

You are calling the template filter in a wrong way. Please see below:
You can not pass the javascript variable into the template filter, passed the variable from context.

<script>
    var age = "{{ pk|pk_into_age }}";
</script>

Assuming pk variable exists in the context. Or hardcode the pk value as:

var age = "{{ '123'|pk_into_age }}";

0👍

You cannot use javascript variable in a template filter, because javascript runs on the client side, while templates are generated on the server side.

As far as I know, there is no way, to bypass this problem, without communicating with the server again.

So, to pass a javascript variable to a template filter, you may, for example, use an ajax request. Write additional view, which processes given pk and returns a plain template, without html headers, just with the data you need.

OR… if you don’t need to communicate with user to get “news” object, just retrieve news.age in the view.

Leave a comment