I know this is an old thread, but I stumbled on it when I was trying to fix the same problem, and I found the solution. The Developer Docs are trying to explain how to do it, but there are a few things missing in that doc, so let me see if I can make it clear.
Let us say you want to localize a string in a sensor. In the example here I have sensor called
sensor.pressure_trend and it can have a state of
rising. I now want to display another string in the UI, based on what language the user has chosen.
In your custom integration, start by adding a
translations directory, if it does not already exist.
Now add a file called
Edit the file and add this
Note the word trend right under *state. We will use this later to identify this specific section in the translations. (It could be any word, just something unique)
Now in your
sensor.py file you must add a few things before this will work:
Import this at the top of your file:
from homeassistant.helpers.typing import StateType
Then when you define your sensor, you must make sure to add a Device Class called “trend” - The same name you used in the json file.
If you use the
SensorEntityDescription this could look like this for the Pressure Trend sensor:
The only thing you need to do now, is just to add the
StateType to the
native_value property, like this:
def native_value(self) -> StateType:
"""Return the state of the sensor."""
And that is it. If you run the program now it will translate the state of your sensor to what is on the right side of the colon in the json file. And of course you can then add more files like
sensor.da.json for danish, etc.
And you can also add more sections in the json file, with more translations for other sensors. Just remember that the sensor must have a device_class equal to the section.
Feel free to poke around in one of my custom integrations, which has implemented this
Hope this helps someone looking for the same answer like I did.