Agrega cadenas localizables a temas y componentes de tema

For those looking to add custom languages and translations to a Discourse theme or theme component, they can now include localised strings, which are made available for use in UI components. Translations are stored in the same format as core/plugin translations, and can be used in almost the same way.

Themes can supply translation files in a format like /locales/{locale}.yml. These files should be valid YAML, with a single top level key equal to the locale being defined. These can be defined using the discourse_theme CLI, importing a .tar.gz, installing from a GIT repository, or via the editor on theme-creator.discourse.org.

An example locale file might look like

en:
  theme_metadata:
    description: "This is a description for my theme"
    settings:
      theme_setting_name: "This is a description for the setting `theme_setting_name`"
      another_theme_setting_name:
        description: "This is a description for the setting `another_theme_setting_name`"
  sidebar:
    welcome: "Welcome"
    back: "back,"
    welcome_subhead: "We're glad you're here!"
    likes_header: "Share the Love"
    badges_header: "Your Top Badges"
    full_profile: "View your full profile"

Administrators can override individual keys on a per-theme basis in the /admin/customize/themes user interface. Fallback is handled in the same way as core, so it is ok to have incomplete translations for non-english languages will make use of the english keys.

In the background, these translations are stored alongside the core translations, under a theme-specific namespace. For example:

theme_translation.{theme_id}.sidebar.welcome

You should never hardcode the theme_id in your theme code, so there are a few ways to help you access the translations.

In .hbs files, you can use the dedicated helper

{{theme-i18n "my_translation_key"}}

Or, if you need to pass the translation key into another component, you can use the theme-prefix helper:

<DButton @label={{theme-prefix "my_translation_key"}} />

In Javascript, or in .gjs files, you can use the themePrefix function. This is automatically injected, and does not need to be imported:

const result = I18n.t(themePrefix("my_translation_key"));

<template>{{i18n (themePrefix "blah")}}</template>

For a complete example of using translations in a theme, check out @awesomerobot’s Fakebook theme: GitHub - discourse/Fakebook


This document is version controlled - suggest changes on github.

31 Me gusta

Howto use theme translations in CSS ? I know we can use theme parameters but I need theme translations.

You can’t, they’re only available in templates and javascript. That’s the same as core/plugin translations.

Ideally, refactor things so that the string is set in a template. But if you really need a customisable string in a css file, you could use theme settings: Developer’s guide to Discourse Themes

1 me gusta

And if I use theme setting, is it possible to translate it ?

No, not in to multiple languages, but it would allow admins to customize it for their site.

2 Me gusta

Hello everyone.
I’m redefining the template upload-selector.hbs
I want to add a translatable phrase.
I created a new variable upload_selector.upload_images
For example

Please tell me what to do next?

Hello,

when i try this technic in the discourse theme creator (see here) everything works fine and as explained here in the post.

However if I import the very same theme on my own server only " [en.theme_translations.12.blog]" appears. Also in the theme settings page there is no “Theme Translations” section like on the theme creator.

I really don’t know where to search for this error anymore. Has anybody a hint for me?

[Edit]
I’m using discourse 2.6.7 ( [f73cdbbd2f ] ) in an docker environment.

can you update discourse ?

you are using an old version

Yeah i’m trying that, that is another thing i need help with but, I don’t want to post it here, that’s another topic.

Anyway I thought that shouldn’t be problem as the translation feature was included in version 2.2.0.beta9, see commit.

Hola, disculpa de antemano por la pregunta de novato.
Creé un encabezado solo con html y css

        <div class="top-navbar">
         <span class="j_menu_item" ><a>Download</a></span>     
        </div>

Y luego quiero traducir la palabra “Download”
Creé el archivo de traducción al inglés

en: 
  top-navbar: 
    download: "Yeah"

Luego cambié el código html como en el ejemplo de facebook


    <script type="text/x-handlebars" data-template-name="/connectors/discovery-below/sidebar">
        <div class="top-navbar">
         <a href="https://www.example.com/download">{{i18n (theme-prefix "top-navbar.download")}}</a></span>     
        </div>
    </script>

Esto traduce e imprime “Yeah” pero rompe mi diseño, supongo que es porque estoy usando “/connectors/discovery-below/sidebar”. Solo quiero aplicar mi traducción sin modificar ninguna plantilla, pero no entiendo cómo aplicar la traducción en línea.

¿Podrías proporcionar un ejemplo simple sobre cómo usar una traducción en el html personalizado de un tema?

¡Gracias!

Hola,

El problema es que data-template-name debe ser un nombre único. Developing Discourse Themes & Theme Components. Como esto: data-template-name=\"/connectors/PLUGIN-OUTLET-NAME/UNIQUE-NAME\" Ahora usas el nombre sidebar en tu ejemplo, que creo que anula la plantilla de la barra lateral de Facebook.

Por ejemplo, esto debería funcionar :slightly_smiling_face:

<script type="text/x-handlebars" data-template-name="/connectors/discovery-below/downloadlink">
  <div class="top-navbar">
    <span class="j_menu_item" ><a href="https://www.example.com/download">{{i18n (theme-prefix "top-navbar.download")}}</a></span>     
  </div>
</script>
2 Me gusta

Gracias @Don

Olvidé mencionar que el plugin no está instalado y que ya intenté cambiar el data-template-name por un UNIQUE-NAME aleatorio con el mismo resultado o que mi banner no aparezca en absoluto si inventé el PLUGIN-OUTLET-NAME.
Probablemente puedas notar ahora, no estoy familiarizado en absoluto con handlebars/ember :slight_smile:
Entiendo que estoy personalizando una plantilla que tiene su lugar predefinido en el html y el resultado es que el html personalizado ya no está en /html/body/section main sino en lo más profundo, lo que resulta en una herencia de CSS que no tenía antes.
Lo que me cuesta entender es ¿Por qué necesito personalizar alguna plantilla para usar una traducción…?
Logré identificar la plantilla a personalizar usando Ember inspector como se aconsejó aquí
Y gracias a tu respuesta y enlace sobre el plugin-outlet encontré el data-template-name correcto = “/connectors/above-site-header/my-navbar”
Gracias de nuevo por tu ayuda.

1 me gusta

Ya veo… Pensé que estabas usando el tema Fakebook y querías colocar tu código debajo de la sección de la barra lateral. :slightly_smiling_face:

Una buena manera de ver las salidas de complementos visualmente es usar el componente temático Ubicaciones de salidas de complementos.

2 Me gusta

Hola @Don,

La razón por la que usé ese ejemplo de Facebook es por:

¡Gracias de nuevo!

¿Qué pasa con el singular y el plural, cómo traducir texto usando {{theme-i18n}} si tiene una y muchas traducciones? Por ejemplo, “Resultado” y “Resultados”.

2 Me gusta

Hay algunos ejemplos de cómo hacemos esto en el código fuente de Discourse, normalmente tenemos dos cadenas y cambiamos según un entero:

Screenshot 2022-12-15 at 5.42.58 PM

Esto debería funcionar también en un tema, generalmente el JS se vería algo así:

I18n.t(themePrefix("confirm_remove_tags"), {
  count: exampleCountValue,
});
1 me gusta

¿y qué hay de hbs, se puede hacer en plantillas hbs?

1 me gusta

Sí, puede:

{{theme-i18n "confirm_remove_tags" count=this.exampleCountValue}}
4 Me gusta

cuando hago eso en una plantilla de componente .gjs dentro de un Tema, obtengo:

Error: Attempted to resolve a helper in a strict mode template, but that value was not in scope: theme-prefix

Así que intento importarlo:

import themePrefix from "discourse/helpers/theme-prefix";

Pero refunfuña:

Identifier 'themePrefix' has already been declared

(Busqué un ejemplo en el 'hub pero no parece haber ninguno)

1 me gusta

Actualización: necesitas usar {{i18n (themePrefix "

4 Me gusta