Skip to content

Commit

Permalink
Merge pull request #584 from getformwork/feature/template-translations
Browse files Browse the repository at this point in the history
Translate template titles and decouple template translation strings from panel
  • Loading branch information
giuscris authored Oct 6, 2024
2 parents d1978be + c4a48a0 commit 272e428
Show file tree
Hide file tree
Showing 24 changed files with 253 additions and 192 deletions.
42 changes: 39 additions & 3 deletions formwork/src/Schemes/Scheme.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
use Formwork\Fields\FieldCollection;
use Formwork\Fields\FieldFactory;
use Formwork\Fields\Layout\Layout;
use Formwork\Translations\Translation;
use Formwork\Translations\Translations;
use Formwork\Utils\Arr;
use Formwork\Utils\Str;
use InvalidArgumentException;

class Scheme implements Arrayable
Expand All @@ -20,6 +22,8 @@ class Scheme implements Arrayable
*/
protected string $path;

protected string $title;

protected SchemeOptions $options;

/**
Expand All @@ -33,8 +37,6 @@ public function __construct(protected string $id, array $data, protected Transla
$this->extend($this->schemes->get($this->data['extend']));
}

$this->data['title'] ??= $this->id;

$this->options = new SchemeOptions($this->data['options'] ?? []);
}

Expand All @@ -56,7 +58,20 @@ public function id(): string
*/
public function title(): string
{
return $this->data['title'];
if (isset($this->title)) {
return $this->title;
}

$title = $this->data['title'] ?? $this->id;

if (isset($this->data['title'])) {
try {
$title = $this->translate($title, $this->translations->getCurrent());
} catch (InvalidArgumentException) {
}
}

return $this->title = $title;
}

/**
Expand All @@ -83,4 +98,25 @@ protected function extend(Scheme $scheme): void

$this->data = array_replace_recursive($scheme->data, $this->data);
}

protected function translate(mixed $value, Translation $translation): mixed
{
$language = $translation->code();

if (is_array($value)) {
if (isset($value[$language])) {
$value = $value[$language];
}
} elseif (!is_string($value)) {
return $value;
}

$interpolate = fn ($value) => is_string($value) ? Str::interpolate($value, fn ($key) => $translation->translate($key)) : $value;

if (is_array($value)) {
return Arr::map($value, $interpolate);
}

return $interpolate($value);
}
}
13 changes: 12 additions & 1 deletion formwork/src/Templates/Template.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Closure;
use Formwork\App;
use Formwork\Assets;
use Formwork\Schemes\Scheme;
use Formwork\Site;
use Formwork\Utils\Constraint;
use Formwork\Utils\FileSystem;
Expand All @@ -25,7 +26,7 @@ class Template implements Stringable
/**
* Create a new Template instance
*/
public function __construct(protected string $name, protected App $app, protected Site $site, protected ViewFactory $viewFactory)
public function __construct(protected string $name, protected Scheme $scheme, protected App $app, protected Site $site, protected ViewFactory $viewFactory)
{
$this->path = $this->app->config()->get('system.templates.path');
}
Expand All @@ -40,6 +41,16 @@ public function name(): string
return $this->name;
}

public function scheme(): Scheme
{
return $this->scheme;
}

public function title(): string
{
return $this->scheme->title();
}

public function path(): string
{
return $this->path;
Expand Down
8 changes: 6 additions & 2 deletions formwork/src/Templates/TemplateFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@

namespace Formwork\Templates;

use Formwork\Schemes\Schemes;
use Formwork\Services\Container;

class TemplateFactory
{
public function __construct(protected Container $container)
public function __construct(protected Container $container, protected Schemes $schemes)
{
}

public function make(string $name): Template
{
return $this->container->build(Template::class, compact('name'));
return $this->container->build(Template::class, [
'name' => $name,
'scheme' => $this->schemes->get('pages.' . $name),
]);
}
}
23 changes: 23 additions & 0 deletions formwork/translations/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,30 @@ fields.array.add: Hinzufügen
fields.array.remove: Entfernen
fields.file.uploadLabel: <strong>Klicken</strong>, um eine Datei auszuwählen oder <strong>ziehen</strong>, um sie hier abzulegen
fields.select.empty: Keine passenden Optionen
page.attributes: Attribute
page.cacheable: Im Cache speichern
page.content: Inhalt
page.files: Dateien
page.image: Bild
page.listed: Im Menü sichtbar
page.noImage: Kein Bild
page.none: (Keine)
page.noTags: Keine Tags
page.options: Optionen
page.page: Seite
page.parent: Übergeordnete Seite
page.postsPerPage: Beiträge pro Seite
page.publishDate: Veröffentlichungsdatum
page.routable: Routbar
page.status.notPublished: Nicht veröffentlicht
page.status.notRoutable: Nicht routbar
page.status.published: Veröffentlicht
page.summary: Zusammenfassung
page.tags: Tags
page.template: Vorlage
page.text: Text
page.title: Titel
page.unpublishDate: Veröffentlichungsdatum aufheben
upload.error: Datei kann nicht hochgeladen werden. %s.
upload.error.alreadyExists: Eine Datei mit demselben Namen existiert bereits
upload.error.cannotMoveToDestination: Hochgeladene Datei kann nicht an das Ziel verschoben werden
Expand Down
23 changes: 23 additions & 0 deletions formwork/translations/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,30 @@ fields.array.add: Add
fields.array.remove: Remove
fields.file.uploadLabel: <strong>Click</strong> to choose a file to upload or <strong>drag</strong> it here
fields.select.empty: No matching options
page.attributes: Attributes
page.cacheable: Cacheable
page.content: Content
page.files: Files
page.image: Image
page.listed: Visible in the menu
page.noImage: No image
page.none: (None)
page.noTags: No tags
page.options: Options
page.page: Page
page.parent: Parent page
page.postsPerPage: Posts per page
page.publishDate: Publish date
page.routable: Routable
page.status.notPublished: Not published
page.status.notRoutable: Not routable
page.status.published: Published
page.summary: Summary
page.tags: Tags
page.template: Template
page.text: Text
page.title: Title
page.unpublishDate: Unpublish date
upload.error: Cannot upload file. %s.
upload.error.alreadyExists: A file with the same name already exists
upload.error.cannotMoveToDestination: Failed to move uploaded file to destination
Expand Down
23 changes: 23 additions & 0 deletions formwork/translations/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,30 @@ fields.array.add: Agregar
fields.array.remove: Quitar
fields.file.uploadLabel: <strong>Haz clic</strong> para elegir un archivo para cargar o <strong>arrástralo</strong> aquí
fields.select.empty: No hay opciones coincidentes
page.attributes: Atributos
page.cacheable: En caché
page.content: Contenido
page.files: Archivos
page.image: Imagen
page.listed: Visible en el menú
page.noImage: Sin imagen
page.none: (Ninguno)
page.noTags: Sin etiquetas
page.options: Opciones
page.page: Página
page.parent: Página principal
page.postsPerPage: Publicaciones por página
page.publishDate: Fecha de publicación
page.routable: Enrutable
page.status.notPublished: No publicado
page.status.notRoutable: No enrutable
page.status.published: Publicado
page.summary: Resumen
page.tags: Etiquetas
page.template: Plantilla
page.text: Texto
page.title: Título
page.unpublishDate: Fecha de despublicación
upload.error: No se puede cargar el archivo. %s.
upload.error.alreadyExists: Ya existe un archivo con el mismo nombre
upload.error.cannotMoveToDestination: Error al mover el archivo cargado al destino
Expand Down
23 changes: 23 additions & 0 deletions formwork/translations/fr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,30 @@ fields.array.add: Ajouter
fields.array.remove: Supprimer
fields.file.uploadLabel: <strong>Glisser-déposer</strong> dans la zone ou <strong>cliquer-ici</strong> pour sélectionner un fichier à envoyer.
fields.select.empty: Aucune option correspondante
page.attributes: Attributs
page.cacheable: Activer le cache
page.content: Contenu
page.files: Fichiers
page.image: Image d’accroche
page.listed: Visible dans le menu
page.noImage: Aucune image
page.none: (Aucun)
page.noTags: Aucun tag
page.options: Options
page.page: Page
page.parent: Parent
page.postsPerPage: Articles par page
page.publishDate: Date de publication
page.routable: Accessible
page.status.notPublished: Brouillon
page.status.notRoutable: Inaccessible
page.status.published: Publié
page.summary: Résumé
page.tags: Tags
page.template: Modèle
page.text: Texte
page.title: Titre
page.unpublishDate: Date de péremption
upload.error: Impossible de télécharger le fichier. %s.
upload.error.alreadyExists: Un fichier du même nom existe déjà
upload.error.cannotMoveToDestination: Impossible de déplacer le fichier téléchargé vers la destination
Expand Down
23 changes: 23 additions & 0 deletions formwork/translations/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,30 @@ fields.array.add: Aggiungi
fields.array.remove: Rimuovi
fields.file.uploadLabel: <strong>Fare click</strong> per selezionare un file da caricare o <strong>trascinarlo</strong> qui
fields.select.empty: Nessuna opzione corrispondente
page.attributes: Attributi
page.cacheable: Abilita cache
page.content: Contenuto
page.files: File
page.image: Immagine
page.listed: Visibile nel menu
page.noImage: Nessuna immagine
page.none: (Nessuna)
page.noTags: Nessun tag
page.options: Opzioni
page.page: Pagina
page.parent: Pagina superiore
page.postsPerPage: Post per pagina
page.publishDate: Data di pubblicazione
page.routable: Raggiungibile
page.status.notPublished: Non pubblicato
page.status.notRoutable: Non raggiungibile
page.status.published: Pubblicato
page.summary: Riassunto
page.tags: Tag
page.template: Template
page.text: Testo
page.title: Titolo
page.unpublishDate: Data di rimozione
upload.error: Impossibile caricare il file. %s.
upload.error.alreadyExists: Un file con lo stesso nome esiste già
upload.error.cannotMoveToDestination: Impossibile spostare il file caricato alla destinazione
Expand Down
23 changes: 23 additions & 0 deletions formwork/translations/pt.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,30 @@ fields.array.add: Adicionar
fields.array.remove: Remover
fields.file.uploadLabel: <strong>Clique</strong> aqui para escolher um ficheiro para enviar ou <strong>arrastar</strong> para aqui.
fields.select.empty: Sem opções correspondentes
page.attributes: Atributos
page.cacheable: Cache
page.content: Conteúdo
page.files: Ficheiros
page.image: Imagem
page.listed: Visível no menu
page.noImage: Sem imagem
page.none: (Nenhum)
page.noTags: Sem tags
page.options: Opções
page.page: Página
page.parent: Página parente
page.postsPerPage: Items por página
page.publishDate: Data de publicação
page.routable: Roteável
page.status.notPublished: Não publicado
page.status.notRoutable: Não roteável
page.status.published: Publicado
page.summary: Resumo
page.tags: Tags
page.template: Template
page.text: Texto
page.title: Titulo
page.unpublishDate: Data de cancelamento da publicação
upload.error: Não é possível fazer upload do ficheiro. %s.
upload.error.alreadyExists: Já existe um ficheiro com o mesmo nome
upload.error.cannotMoveToDestination: Falha ao mover o ficheiro enviado para o destino
Expand Down
23 changes: 23 additions & 0 deletions formwork/translations/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,30 @@ fields.array.add: Добавлять
fields.array.remove: Удалить
fields.file.uploadLabel: <strong>Нажмите</strong> чтобы выбрать файл для загрузки или <strong>тянуть</strong> это здесь
fields.select.empty: Нет подходящих вариантов
page.attributes: Атрибуты
page.cacheable: Кешируемый
page.content: Содержание
page.files: Файлы
page.image: Изображение
page.listed: Видимо в меню
page.noImage: Нет изображения
page.none: (Нет)
page.noTags: Нет тегов
page.options: Параметры
page.page: Страница
page.parent: Родитель страницы
page.postsPerPage: Сообщения на странице
page.publishDate: Дата публикации
page.routable: Маршрутизируемый
page.status.notPublished: Не Опубликовано
page.status.notRoutable: Не маршрутизируемый
page.status.published: Опубликованный
page.summary: Сводка
page.tags: Теги
page.template: Шаблон
page.text: Текст
page.title: Заглавие
page.unpublishDate: Дата Отменить публикацию
upload.error: Невозможно загрузить файл. %s.
upload.error.alreadyExists: Файл с таким именем уже существует
upload.error.cannotMoveToDestination: Не удалось переместить загруженный файл в папку назначения
Expand Down
Loading

0 comments on commit 272e428

Please sign in to comment.