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!

IsiKleo
  • 11
  • 2

2 Answers2

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);
IsiKleo
  • 11
  • 2
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');
Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
mh-firouzjah
  • 834
  • 1
  • 6
  • 15
  • 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). – IsiKleo Jul 19 '19 at 09:06
  • You could have the templtag code in a var in Js and then paste that vars value to the title. – mh-firouzjah Jul 19 '19 at 10:36
  • and be careful about cotations – mh-firouzjah Jul 19 '19 at 10:38