M3 Solaris
Guía de addons: crearlos, empaquetarlos y subirlos. Addon guide: how to build them, zip them and upload them.
Qué es un addonWhat an addon is
Un addon es una carpeta con un manifiesto y una plantilla. Nada más: no hay clases que extender, ni registro en la base de datos, ni instalador de Joomla. Si la carpeta está en su sitio, el addon existe.
An addon is a folder with a manifest and a template. That is all: no class to extend, no database registration, no Joomla installer. If the folder is in place, the addon exists.
notice/
├── addon.json obligatorio · qué es y qué campos tienerequired · what it is and which fields it has
├── template.html obligatorio (salvo addon PHP) · el HTMLrequired (unless a PHP addon) · the HTML
├── site.css opcional · estilos en el sitio y en el lienzooptional · styles on the site and in the canvas
├── site.js opcional · JavaScript en el sitiooptional · JavaScript on the site
├── admin.css opcional · estilos solo en el constructoroptional · styles in the builder only
├── site.php opcional · render en el servidoroptional · server-side rendering
└── icon.svg opcional · icono de la paletaoptional · palette icon
El nombre de la carpeta y el name del manifiesto tienen que coincidir, en minúsculas y sin guiones: miaddon, no mi-addon. Es la regla que más veces se salta al empezar.
The folder name and the name in the manifest have to match, lowercase and without dashes: myaddon, not my-addon. That is the rule people break most often.
Bloque o addon. Un bloque (fila, columna, título, imagen…) es HTML normal que editas en el lienzo. Un addon es una pieza con formulario propio: guarda sus ajustes en el artículo y vuelve a pintarse a partir de ellos. Si lo que quieres es «un trozo de HTML fijo», usa un bloque; si quieres «lo mismo con campos que cambian», haz un addon.
Block or addon. A block (row, column, heading, image…) is ordinary HTML you edit on the canvas. An addon is a piece with a form of its own: it stores its settings in the article and redraws itself from them. If you want “a fixed piece of HTML”, use a block; if you want “the same thing with fields that change”, build an addon.
El addon mínimoThe smallest addon
Dos archivos y ya aparece en la paleta. notice/addon.json:
Two files and it shows up in the palette. notice/addon.json:
{
"name": "notice",
"title": { "es-ES": "Aviso", "en-GB": "Notice" },
"description": { "es-ES": "Una caja de aviso con título y texto.", "en-GB": "A notice box with a title and text." },
"icon": "bi bi-exclamation-triangle",
"category": "content",
"version": "1.0.0",
"render": "template",
"wrapper": { "tag": "div", "class": "notice-box" },
"fields": [
{ "name": "title", "type": "text",
"label": { "es-ES": "Título", "en-GB": "Title" }, "default": "" },
{ "name": "body", "type": "html", "rows": 3,
"label": { "es-ES": "Texto", "en-GB": "Text" }, "default": "<p></p>" },
{ "name": "tone", "type": "select", "default": "warning",
"label": { "es-ES": "Tono", "en-GB": "Tone" },
"options": [
{ "value": "warning", "label": { "es-ES": "Aviso", "en-GB": "Warning" } },
{ "value": "danger", "label": { "es-ES": "Peligro", "en-GB": "Danger" } },
{ "value": "info", "label": { "es-ES": "Información", "en-GB": "Info" } }
] }
]
}
notice/template.html:
notice/template.html:
<div class="alert alert-{{tone}}">
{{#if title}}<h4 class="alert-heading">{{title}}</h4>{{/if}}
{{{body}}}
</div>
Sube la carpeta comprimida (ver Empaquetar) y el addon estará en la paleta con su formulario generado a partir de fields. No hay más pasos.
Zip the folder (see Zip it) and upload it: the addon appears in the palette with the form generated from fields. There are no further steps.
addon.json
| ClaveKey | Qué haceWhat it does |
|---|---|
name | Identificador. Minúsculas, letras y números, igual que la carpeta. No se puede cambiar sin romper los artículos ya guardados.The identifier. Lowercase letters and digits, the same as the folder. Changing it breaks articles already saved. |
title | Nombre visible en la paleta y en el panel.The name shown in the palette and the panel. |
description | Una línea; sale en el tooltip de la paleta.One line; it shows in the palette tooltip. |
icon | Clase de icono (bi bi-star, fa-solid fa-star) o el nombre de un archivo de imagen de la propia carpeta. Si lo omites se usa icon.svg.An icon class (bi bi-star, fa-solid fa-star) or the file name of an image in the folder itself. Omit it and icon.svg is used. |
category | Agrupa los iconos en la paleta. Inventa la que quieras.Groups the icons in the palette. Invent whichever you like. |
version | Tuya. Además sirve de cache-buster de site.css y site.js.Yours. It also cache-busts site.css and site.js. |
render | template (por defecto) o(default) or php. |
wrapper | tag y class del elemento que envuelve la instancia. El constructor añade siempre bsl-addon y bsl-addon-<name>.tag and class of the element wrapping the instance. The builder always adds bsl-addon and bsl-addon-<name>. |
fields | El formulario. Ver abajo.The form. See below. |
canvasJs | true para que site.js también se cargue dentro del lienzo (carruseles, contadores…).true so site.js also loads inside the canvas (carousels, counters…). |
preview | HTML de sustitución en el lienzo para addons PHP sin plantilla.Stand-in HTML in the canvas for PHP addons with no template. |
Un campoOne field
| ClaveKey | Qué haceWhat it does |
|---|---|
name | Cómo se llama la variable en la plantilla. Letras, números y _.What the variable is called in the template. Letters, digits and _. |
type | Ver la tabla siguiente.See the next table. |
label | Etiqueta del control.Label of the control. |
hint | Texto de ayuda bajo el control.Help text under the control. |
default | Valor con el que nace la instancia.The value a new instance starts with. |
showon | Muestra el campo solo si se cumple: "image" (no vacío), "tone:danger", "kind:a|b" (cualquiera de los dos), "!flat" (negado), y varias reglas separadas por coma se cumplen todas.Shows the field only when it matches: "image" (not empty), "tone:danger", "kind:a|b" (either), "!flat" (negated); several rules separated by commas must all match. |
Tipos de campoField types
| TipoType | ControlControl | ValorValue |
|---|---|---|
text | Una líneaOne line | string |
textarea | Varias líneas · rowsSeveral lines · rows | string |
html | Varias líneas monoespaciadasSeveral lines, monospaced | string · úsalo con {{{ }}}string · use it with {{{ }}} |
lines | Una entrada por líneaOne entry per line | array de strings · recórrelo con {{#each}}array of strings · walk it with {{#each}} |
number | min max step | number |
range | DeslizadorSlider | number |
select | options: [{ value, label }] | string |
checkbox | CasillaCheckbox | booleano · úsalo con {{#if}}boolean · use it with {{#if}} |
color | Selector + textoPicker + text | #rrggbb |
image | Gestor multimedia de JoomlaJoomla media manager | rutapath |
folder | Una carpeta de images/, recorrida y no escrita: enseña sus fotos y sus subcarpetas con cuántas fotos tiene cada una; abrir una es elegirla (5.21.0). En site.php se lee con MediaFolders::images($ruta, $subcarpetas), que no sale nunca de images/A folder of images/, walked rather than typed: it shows its pictures and its subfolders with how many pictures each holds; opening one is choosing it (5.21.0). In site.php read it with MediaFolders::images($path, $subfolders), which never leaves images/ | ruta · images/…path · images/… |
url · link | Enlace: URL · Artículo · Categoría · Menú del sitio, el mismo control que el botón y la imagen. Elegir un artículo escribe su dirección (SEF); el ajuste sigue siendo la dirección y nada másLink: URL · Article · Category · Menu of the site, the same control as the button and the image. Picking an article writes its address (SEF); the setting is still the address and nothing else | string |
icon | Selector de Bootstrap IconsBootstrap Icons picker | claseclass |
repeater | Lista de elementos · fields, itemLabel, addLabel, min, maxList of items · fields, itemLabel, addLabel, min, max | array de objetosarray of objects |
group | Abre una pestaña: todo lo que va detrás pertenece a ellaOpens a tab: everything after it belongs to it | — |
note | Un aviso en el formularioA remark in the form | — |
Pestañas con groupTabs with group
A partir de dos grupos el formulario se convierte en pestañas. Los campos escritos antes del primer group van a una pestaña «General».
From two groups on, the form becomes tabs. Fields written before the first group go into a “General” tab.
{ "name": "title", "type": "text", "label": "Título" },
{ "name": "groupStyle", "type": "group", "label": "Estilo" },
{ "name": "tone", "type": "select", "label": "Tono", "options": [ … ] }
Opciones que son carpetas: optionsDirOptions that are folders: optionsDir
Un select con "optionsDir": "layouts" ofrece, además de sus options, una opción por cada subcarpeta de <addon>/layouts/ y de media/bslayout/extend/<addon>/layouts/ que tenga un option.json. El nombre de la carpeta es el valor; title (traducible) la etiqueta; ordering su sitio. Su option.css y su option.js, si existen, viajan con el site.css y el site.js del addon: al sitio, al lienzo y a la vista previa. Añadir una opción es copiar una carpeta, y la de extend sobrevive a las actualizaciones; si se llama como una de fábrica, la sustituye (en su mismo sitio del desplegable). Es lo que usa la Galería Isotope para sus layouts.
A select with "optionsDir": "layouts" offers, besides its options, one option per subfolder of <addon>/layouts/ and of media/bslayout/extend/<addon>/layouts/ that holds an option.json. The folder name is the value; title (translatable) the label; ordering its place. Its option.css and option.js, when present, travel with the addon's site.css and site.js: to the site, the canvas and the preview. Adding an option is copying a folder, and the one in extend survives updates; named like a shipped one, it replaces it (in the same place of the list). The Isotope gallery uses it for its layouts.
media/bslayout/extend/isogallery/layouts/polaroid/
option.json { "title": { "es-ES": "Polaroid", "en-GB": "Polaroid" }, "ordering": 8 }
option.css .bsl-iso.is-polaroid .bsl-iso-item { padding: 8px 8px 28px; background: #fff; }
option.js (opcional: sólo si el layout coloca las fotos él)(optional: only if the layout places the pictures itself)
Listas con repeaterLists with repeater
{
"name": "items",
"type": "repeater",
"label": "Preguntas",
"itemLabel": "question",
"addLabel": "Añadir pregunta",
"fields": [
{ "name": "question", "type": "text", "label": "Pregunta" },
{ "name": "answer", "type": "html", "label": "Respuesta", "rows": 3 }
],
"default": [ { "question": "¿Cómo funciona?", "answer": "<p>Así.</p>" } ]
}
Un repetidor no puede contener otro repetidor ni un group.
A repeater cannot contain another repeater, nor a group.
La plantillaThe template
Un solo motor, escrito dos veces —en JavaScript para el lienzo y en PHP para el sitio— y con una suite que compara las dos salidas en cada versión. Lo que ves en el constructor es lo que recibe el visitante.
One engine, written twice — in JavaScript for the canvas and in PHP for the site — with a suite that compares both outputs on every release. What you see in the builder is what the visitor gets.
| SintaxisSyntax | Qué haceWhat it does |
|---|---|
{{name}} | El valor, escapado. Lo normal.The value, escaped. The usual one. |
{{{name}}} | El valor tal cual, sin escapar. Para campos html.The value as is, unescaped. For html fields. |
{{#if x}}…{{else}}…{{/if}} | Vacío, 0 y false cuentan como falso.Empty, 0 and false count as false. |
{{#unless x}}…{{/unless}} | Al revés.The other way round. |
{{#each items}}…{{/each}} | Con {{else}} para la lista vacía.With {{else}} for the empty list. |
{{@index}} {{@number}} | Posición dentro de each, desde 0 y desde 1.Position inside each, from 0 and from 1. |
{{@first}} {{@last}} | Para el primero y el último.For the first and the last one. |
{{.}} | El elemento actual cuando la lista es de strings (campo lines).The current item when the list holds strings (a lines field). |
{{image.src}} | Ruta con punto; dentro de each también busca en el contexto de fuera.Dotted path; inside each it also looks in the outer context. |
{{@uid}} | Identificador único por instancia. Imprescindible para acordeones, pestañas y modales.A unique id per instance. Essential for accordions, tabs and modals. |
{{> campo}} | Renderiza el valor de ese campo como si fuera una plantilla. Es lo que permite que sea el editor quien escriba la maquetación.Renders the value of that field as a template. This is what lets the editor write the layout. |
{{> [campo]}} | Lee campo, y lo que valga es el nombre del campo que contiene la plantilla. Sirve para elegir plantilla por elemento.Reads campo, and its value is the name of the field holding the template. Use it to pick a layout per item. |
Un acordeón, con {{@uid}} para que dos instancias en la misma página no se peleen:
An accordion, with {{@uid}} so two instances on one page do not fight:
<div class="accordion" id="faq-{{@uid}}">
{{#each items}}
<div class="accordion-item">
<h3 class="accordion-header">
<button class="accordion-button{{#unless @first}} collapsed{{/unless}}" type="button"
data-bs-toggle="collapse" data-bs-target="#faq-{{@uid}}-{{@number}}">{{question}}</button>
</h3>
<div id="faq-{{@uid}}-{{@number}}" class="accordion-collapse collapse{{#if @first}} show{{/if}}"
data-bs-parent="#faq-{{@uid}}">
<div class="accordion-body">{{{answer}}}</div>
</div>
</div>
{{/each}}
</div>
Un {{> }} se expande como mucho cinco veces. Si un campo se incluye a sí mismo, el motor corta y no se cuelga. Y el nombre tiene que ser un campo a secas: no se aceptan rutas ni expresiones.
A {{> }} expands five levels at most. If a field includes itself the engine stops instead of hanging. And the name has to be a plain field: no paths, no expressions.
site.css · site.js · admin.css
Si existen, se cargan solos. site.css va al sitio y al lienzo, así que el constructor se ve como la página. admin.css solo al lienzo, para cuando algo necesita ayuda dentro del editor. site.js va al sitio; añade "canvasJs": true si además lo necesitas dentro del lienzo.
If they exist, they load on their own. site.css goes to the site and to the canvas, so the builder looks like the page. admin.css goes to the canvas only, for when something needs a hand inside the editor. site.js goes to the site; add "canvasJs": true when you also need it in the canvas.
Ata tus estilos a la clase del envoltorio para no tocar el resto de la página:
Anchor your styles to the wrapper class so the rest of the page is left alone:
.bsl-addon-notice .alert { border-left: 3px solid currentColor; }
site.php
Cuando el HTML depende de datos —artículos, la hora, algo aleatorio en cada visita— pon "render": "php" y añade site.php. Recibe cuatro variables y devuelve (o imprime) el HTML interior:
When the HTML depends on data — articles, the time, something random on each visit — set "render": "php" and add site.php. It gets four variables and returns (or prints) the inner HTML:
$settings | array con los valores de la instanciaarray of the instance values |
$addon | la definición leída de addon.jsonthe definition read from addon.json |
$content | el HTML que la instancia tiene ahorathe HTML the instance currently holds |
$app | la aplicación de Joomlathe Joomla application |
<?php
\defined('_JEXEC') or die;
$limit = max(1, min(50, (int) ($settings['limit'] ?? 3)));
ob_start(); ?>
<div class="mi-lista">…</div>
<?php
return ob_get_clean();
Cuándo se vuelve a pintar. Los addons PHP se pintan en cada visita: por eso el azar y la hora funcionan. Los addons de plantilla se guardan ya pintados dentro del artículo y no se vuelven a pintar, salvo que actives Volver a renderizar plantillas en las opciones del plugin de contenido.
When it is redrawn. PHP addons render on every visit: that is why randomness and the clock work. Template addons are stored already rendered inside the article and are not redrawn, unless you switch on Re-render templates in the content plugin options.
Un addon PHP puede tener también template.html: el lienzo lo usa para pintar al instante mientras pide al servidor el resultado de verdad.
A PHP addon can have a template.html as well: the canvas draws it instantly while it asks the server for the real thing.
Ejecutar PHP de addons se puede desactivar en las opciones del componente. Si administras un sitio con varios editores, tenlo en cuenta: un site.php es código con todos los permisos de Joomla.
Running addon PHP can be switched off in the component options. If you run a site with several editors, keep that in mind: a site.php is code with every Joomla permission.
Varios idiomasSeveral languages
Cualquier texto del manifiesto puede ser un objeto con etiquetas de idioma. Se elige el del interfaz, y si no está, el primero.
Any text in the manifest can be an object keyed by language tag. The interface language wins; if it is missing, the first one does.
"title": { "es-ES": "Aviso", "en-GB": "Notice" },
"fields": [
{ "name": "title", "type": "text",
"label": { "es-ES": "Título", "en-GB": "Title" },
"default": { "es-ES": "Atención", "en-GB": "Heads up" } }
]
Empaquetar en zipZip it
El zip contiene la carpeta del addon, o directamente sus archivos. Las dos formas valen:
The zip holds the addon folder, or its files directly. Both work:
notice.zip
└── notice/
├── addon.json
└── template.html
o bienor
notice.zip
├── addon.json
└── template.html
Desde la terminal, dentro de la carpeta que contiene notice/:
From a terminal, in the folder that contains notice/:
zip -r notice.zip notice -x "*.DS_Store" "__MACOSX/*"
En macOS con el Finder: clic derecho sobre la carpeta → Comprimir. Funciona igual; el .DS_Store que mete dentro se ignora.
On macOS with Finder: right-click the folder → Compress. It works the same; the .DS_Store it slips in is ignored.
SubirloUpload it
- Abre el constructor visual en un artículo y pulsa Gestionar, arriba a la derecha de la lista de addons. También puedes ir a Componentes → M3 Solaris → Addons.
- Open the visual builder on an article and press Manage, at the top right of the addon list. You can also go to Components → M3 Solaris → Addons.
- Pulsa Subir addon y elige el zip.
- Press Upload addon and choose the zip.
- Aparece en la lista. Vuelve al constructor: la paleta se recarga sola al cerrar el gestor.
- It appears in the list. Go back to the builder: the palette reloads by itself when the manager closes.
Los addons que subes van a media/com_bslayout/custom/<nombre>/, aparte de los que trae el componente. Así una actualización nunca te pisa los tuyos, y desinstalar el componente no se los lleva por delante.
Addons you upload land in media/com_bslayout/custom/<name>/, apart from the ones the component ships. That way an update never overwrites yours, and uninstalling the component does not take them with it.
Si subes un addon con un nombre que ya existe, se reemplaza. Es la forma normal de publicar una versión nueva.
Uploading an addon whose name already exists replaces it. That is the normal way to publish a new version.
Gestionar y compartirManage and share
- Descargar — te devuelve el zip de cualquier addon, incluidos los que vienen con el componente. Es la mejor plantilla para empezar el tuyo: descarga uno parecido, cámbiale el
namey súbelo. - Download — hands you the zip of any addon, the ones shipped included. It is the best starting point for your own: download a similar one, change its
nameand upload it. - Activar / desactivar — un addon desactivado desaparece de la paleta, pero los artículos que ya lo usan siguen mostrando su HTML.
- Enable / disable — a disabled addon vanishes from the palette, while articles already using it keep showing its HTML.
- Borrar — solo los subidos por ti. Los artículos que lo usaban conservan el HTML tal como quedó guardado.
- Delete — only the ones you uploaded. Articles that used it keep the HTML exactly as it was saved.
- Nuevo addon — el formulario del componente crea el esqueleto sin salir del navegador.
- New addon — the component form creates the skeleton without leaving the browser.
Nada depende de la base de datos. Los ajustes de cada instancia viven en el HTML del artículo, en data-bsl-settings. Si mañana desinstalas el componente, los artículos siguen mostrando su último HTML: pierdes la edición visual, no el contenido.
Nothing depends on the database. The settings of each instance live in the article HTML, in data-bsl-settings. If you uninstall the component tomorrow, the articles keep showing their last HTML: you lose visual editing, not the content.
Los addons MutadorThe Mutator addons
Dos addons que vienen con el componente y le dan la vuelta a la idea: el HTML lo escribe el editor, en el propio artículo, y los campos lo rellenan. Son la versión para este sistema de bloques de contenido editable (tipo div y multi-ítem).
Two addons that ship with the component and turn the idea around: the editor writes the HTML, inside the article itself, and the fields fill it in. They are this system's take on editable div and multi-item content blocks.
Mutador (HTML libre)
Cinco contenidos, tres etiquetas, imagen de escritorio y de móvil, botón, imagen aleatoria, y tres campos de maquetación (antes, principal, después). Variables disponibles:
Five content slots, three labels, a desktop and a mobile image, a button, a random image, and three layout fields (before, main, after). Available variables:
{{{a1}}} … {{{a5}}} {{label1}} {{label2}} {{label3}}
{{image}} {{imageMobile}} {{imageAlt}} {{imageRandom}} {{imageRandomAlt}}
{{buttonText}} {{buttonUrl}} {{buttonAria}} {{{buttonTarget}}}
{{@uid}} {loadmoduleid 16}
Mutador items
Lo mismo con una lista. Cada elemento elige su plantilla entre las cuatro que hayas escrito, y dentro de cada una tienes los valores del elemento y también los comunes:
The same for a list. Each item picks its layout among the four you have written, and inside each one you get the item values and the shared ones too:
{{title}} {{subtitle}} {{{content}}} {{image}} {{imageAlt}} {{imageRandom}}
{{video}} {{label1}} {{label2}} {{buttonText}} {{buttonUrl}} {{{buttonTarget}}}
{{@number}} {{@first}} {{@last}} {{a1}} {{a2}} {{{a3}}}
Por dentro no hay nada especial: su template.html son dos líneas que usan {{> }}, y su site.php baraja, elige la imagen y pasa el resultado por content.prepare. Puedes copiarlos y hacerte el tuyo.
There is nothing special inside: their template.html is two lines using {{> }}, and their site.php shuffles, picks the image and runs the result through content.prepare. Copy them and make your own.
plantilla de Mutador itemsthe Mutator items template
{{> layoutTop}}{{> layout}}{{#each items}}{{> [kind]}}{{/each}}{{> layoutBottom}}
Errores frecuentesCommon mistakes
- El addon no aparece. El
nameno coincide con el nombre de la carpeta, o tiene mayúsculas o guiones. - The addon does not show up. The
namedoes not match the folder name, or it has capitals or dashes. - Sale el HTML como texto. Un campo
htmlcon{{campo}}: usa{{{campo}}}. - HTML shows up as text. An
htmlfield written as{{field}}: use{{{field}}}. - Dos instancias en la página se estorban. Falta
{{@uid}}en losiddel acordeón, las pestañas o el modal. - Two instances on a page interfere.
{{@uid}}is missing from the ids of the accordion, tabs or modal. - El JSON no carga y no dice nada. Una coma de más antes de un
}. Pasa el archivo por un validador de JSON. - The JSON does not load and says nothing. A trailing comma before a
}. Run the file through a JSON validator. - Los cambios de CSS no se ven. Sube el
versiondel manifiesto: es lo que rompe la caché del navegador. - CSS changes do not show. Bump the
versionin the manifest: that is what busts the browser cache. - El azar no cambia. Es un addon de plantilla; el HTML se guardó una vez. Necesita
site.phpy"render": "php". - The random value never changes. It is a template addon; the HTML was stored once. It needs
site.phpand"render": "php".