I am trying to add translate code <?= __('This field is required') ?> in the Magento file using JavaScript but it is not working plz help me.
if(response.length == 0) {
document.getElementById('test').innerHTML = '<span style="color:red;">'<?php __('This field is required') ?>'</span>';
return false;
}
Are any quotes missing or not calling PHP correctly inside JavaScript quotes?
Dhiren Vasoya
9,70914 gold badges37 silver badges61 bronze badges
asked Oct 8, 2021 at 10:44
User0434
1,1552 gold badges17 silver badges41 bronze badges
-
is this is pure js file or phtml?Rizwan Khan– Rizwan Khan2021年10月08日 10:58:08 +00:00Commented Oct 8, 2021 at 10:58
-
@RizwanKhan phml fileUser0434– User04342021年10月08日 12:11:45 +00:00Commented Oct 8, 2021 at 12:11
1 Answer 1
You need to use something like this.
<script type="text/javascript">
require(['mage/translate'], function($t)
{
$t("Your Message Which Need to translate.");
});
</script>
answered Oct 8, 2021 at 10:58
Dhiren Vasoya
9,70914 gold badges37 silver badges61 bronze badges
-
is it not possible to add in my code phtml file.........without adding seperate functionUser0434– User04342021年10月08日 12:10:56 +00:00Commented Oct 8, 2021 at 12:10
-
Yes you can added this code into your phtml file it self. but yes "require" code is necessary.Dhiren Vasoya– Dhiren Vasoya2021年10月08日 12:22:19 +00:00Commented Oct 8, 2021 at 12:22
-
my code is working fine without adding php....after adding php only not working.... why require is necessary it is normal php insertion in javascript right ..this is phtml fileUser0434– User04342021年10月08日 12:44:20 +00:00Commented Oct 8, 2021 at 12:44
-
the javascript is required to added translation object over there, then and then it will translate your string.Dhiren Vasoya– Dhiren Vasoya2021年10月08日 13:26:48 +00:00Commented Oct 8, 2021 at 13:26
-
anyhow my code is working after changing single quotes to double quotes in php tagUser0434– User04342021年10月08日 14:48:44 +00:00Commented Oct 8, 2021 at 14:48
default