0

I want to dynamically translate a html button title attribute in my django project using _("to be translated") or {% trans "to be translated" %} in a javascript file.

The compilation of the .po files for internationalisation works fine for the .html files:

<li data-toggle="popover" title="{%  trans 'to be translated' %}"

In my .js file, I return a HTML element from within a function:

return $('<button title="{%  trans 'to be translated' %}"  type="button" class="gk btn  btn-default pull-right"></button>').click(onclick);

Due to nested quotes ("{% trans 'to be translated' %}" ) and blanks (_("to be translated")) returning a html element from a .js file including a translation does not seem to work.

Is there any workaround for this in django? Thank you!

2 Answers 2

1

Turned out that it was necessary to store the string in a separate variable with the gettext() method.

my_var = gettext("to be translated");

To insert it into html element that is returned by the function, I used a python-like string-formatting function similar to this answer.

The returned html element looks like this:

return $('<button title="{}" type="button" </button>'.format(my_var)).click(onclick);
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure, but if its not important. You could have that btn. In your html file and just make it hide (something like: css display:none.) and by js or jquery. Just do this:

$('#your-btn').attr('title', "{% trans 'to be translated' %}");
$('#your-btn').css('display', 'block');

3 Comments

Thanks for your answer. Unfortunately, this didn't solve my problem. On mouseover, the expression was still visible like this "{% trans 'to be translated' %}". I just managed to solve it by using the gettext() method in a separate variable and formatting the returned html element (see answer below).
You could have the templtag code in a var in Js and then paste that vars value to the title.
<script> var tilte-text = "{% trans 'text to be translated' %}"; $('#your-btn').attr('title', title-text); </script> and be careful about cotations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.