Formularios de marcador de posición

:discourse2: Summary Placeholder Forms will let you build dynamic documentation, by creating a form that replaces any occurrence of a =PATTERN= in your post with the value from a text or selectable input field.
:eyeglasses: Preview Preview on Discourse Theme Creator
:hammer_and_wrench: Repository Link https://github.com/discourse/discourse-placeholder-theme-component
:open_book: New to Discourse Themes? Beginner’s guide to using Discourse Themes

Install this theme component

Features

Add placeholders to posts in this format:

[wrap=placeholder key=NAME description="Your name"][/wrap]
[wrap=placeholder key=COUNTRY default=US defaults=FR,DE,US,CN,AU,CA][/wrap]

Your email: =NAME=-=COUNTRY=@example.com

And this will result in:

This is used in mailing list

Your email: =ZNAME=-=ZCOUNTRY=@example.com

As seen above, text inside the wrapper will be used as a long description.

[wrap=placeholder key=NAME description="Your name"]
This is used in mailing list
[/wrap]

Available keys

  • key: The key that should be replaced in your post
  • default/defaults: default value(s)
  • description: a placeholder text for the input

Examples

# create a new plugin
rails g plugin =PLUGIN_NAME=
cd plugins/=PLUGIN_NAME=

We use it to create runbooks, howtos and reusable templates (it will work in code blocks). Please share your use cases!

Settings

Translation Default
toolbar.builder Add Placeholder
builder.errors.no_key A key is required.
builder.title Add Placeholder
builder.insert Insert
builder.key.label Key
builder.key.description The =Key= to be replaced in the post.
builder.description.label Description
builder.description.description Description displayed on input with no value set.
builder.values.label Default value(s)
builder.values.description Optional value(s) for your placeholder, if multiple values are defined, a select will be used.

:discourse2: Hosted by us? Theme components are available to use on our Standard, Business, and Enterprise plans.

Last edited by @JammyDodger 2024-06-13T22:28:45Z

Check documentPerform check on document:
65 Me gusta

The big issue with math handling like this, is that you need to eval() and eval is unsafe, so you need to use some lib which provide a safe eval with a limited subset of the real eval. I’m unsure we want all this complexity for such a rare case.

6 Me gusta

I tried ! and that would be a neat composer-preview-redux-in-OP kind of thing but… :pensive: I must be missing something, if I understand correctly the Reply Template component takes the raw and looks for “replacers”, but the Placeholder Forms component decorates the cooked?

What I’m trying to do is ease my users into adding some quizz Q&As in a topic, with minimal technical friction, clicks or even key strokes, :heavy-sigh: :roll_eyes:

[wrap=placeholder key="question" description="question"][/wrap]
[wrap=placeholder key="réponse" description="réponse"][/wrap]

[wrap=template key="template-spoiler" action="reply" tagsList="#qui, #quand, #où, #comment"]

## Question
=question=
### Réponse
[spoiler]
=réponse=
[/spoiler]
---
*Étiquette(s) ?*
[/wrap]

which gives

so far so good, but unfortunately, the placeholders =question= and =réponse= are kept in the composer when hitting the template button

Yes I’m not sure what I was thinking when I wrote this… I probably had a different use case in mind, but can’t remember.

It can’t work this way for sure. I will think a little bit about this… Both theme components were experiments at the time and might deserve better treatment as people have been using it quite frequently.

7 Me gusta

Thank you !

happy lets go GIF by Shalita Grant

3 Me gusta

:grin: I don’t know what’s cookin’ in the chef kitchen, but as I usually stuff myself with pistachios or whatnot while waiting, I managed to make it work (for my specific use of course as I’ve almost no idea of what I’m doing, but hey… :sweat_smile: )

4 Me gusta

Ideally I would like to be able to let admin define their own replacers, but eval is risky (and not even possible with a secure csp) so I’m not sure how I could achieve this…

3 Me gusta

First of all - great and really helpful theme component.

But I think I found a bug. If I use a placeholder in a code snippet, that contains backticks (`), it is not working. An example is a SQL code snippet:

DELETE FROM `=TABLENAME=`
WHERE id NOT IN(
        SELECT
            id FROM (
                SELECT
                    id FROM `=TABLENAME=`
                ORDER BY
                    id DESC
                LIMIT 20
) subquery);

TABLENAME gets never replaced (if there is a TABLENAME placeholder).

Sería genial si esto también incluyera algunas condiciones tipo Jinja2. Para que, por ejemplo, alguien pudiera crear una clave red y mapearla al icono :red_circle:, orange se mapearía a :orange_circle:. Pero puedo hacerlo sin eso, por supuesto, pero habría sido genial tener estas condiciones de prueba.

Me encanta este componente. :star_struck:


“¿Y vives realmente de la =NOUN_1=? ¡Qué vida tan =ADJECTIVE_1=!”

“De ella y con ella y de ella y en ella”, dijo =PERSON_1=. “Es mi hermano y mi hermana, y mis tías, y =NOUN_2=, y comida y bebida, y (=ADJECTIVE_2=) =VERBING_1=. Es mi =NOUN_3=, y no quiero otra. Lo que no tiene no vale la pena =VERBING_2=, y lo que no sabe no vale la pena =VERBING_3=. ¡Señor! ¡Las =NOUNS_1= que hemos tenido juntos! Ya sea en invierno o en verano, en primavera o en otoño, siempre tiene su =NOUN_4= y sus =NOUNS_2=. Cuando las =NOUNS_3= están en febrero, y mi =NOUNS_4= y el sótano están repletos de =NOUN_5= que no me sirven, y el =COLOR_1= =NOUN_6= corre junto a mi mejor ventana =NOUN_7=; o de nuevo cuando todo cae =ADVERB_1= y muestra parches de =NOUN_8= que huele a =FOOD_1=, y las =NOUNS_5= y =NOUNS_6= obstruyen los canales, y puedo =VERB_1= sobre =MOISTURE= =NOUN_9= sobre la mayor parte de la =NOUN_10= de ella y encontrar =FOOD_2= fresca para comer, ¡y cosas =ADJECTIVE_3= que la gente ha tirado de =NOUNS_7=!”


Original tomado de la versión de Standard Ebooks de The Wind in the Willows, disponible para leer en línea (busca By it and with it).

10 Me gusta

Hola :wave:

Gracias por este componente :heart: Encaja perfectamente con lo que intento lograr ahora. De hecho, mi primer pensamiento fue que sería genial si se pudiera combinar con el componente Reply Template. Pero desafortunadamente no es posible, como explicaron las publicaciones anteriores. :confused:


He encontrado una solución para usarlo como plantilla, funciona con enlace a nuevos temas y enlace a nuevos mensajes personales.

Así es como lo hice:

  1. Cree un formulario de marcador de posición (para simplificar, uso el ejemplo en OP)

Tu correo electrónico: =NAME=-=COUNTRY=@example.com


  1. Cree un enlace a un nuevo tema:
    Configuré en el enlace:
  2. categoría
  3. título
  4. cuerpo

Si desea agregar líneas vacías, use \ para que no rompa el enlace o para hacerlo invisible, puede usar   que agregará un espacio en la nueva línea. Será parte de la plantilla y creará una línea vacía,

<a href="https://meta.discourse.org/new-topic?category==CATEGORY=&title=This is a topic created by =NAME=&body=Hello :wave:
&nbsp;
This is a test topic... Let's see the placeholder form.
\
Your email: =NAME=-=COUNTRY=@example.com">Use template as new topic</a>

  1. Cree una vista previa del tema

Categoría seleccionada

=CATEGORY=

Título del tema

This is a topic created by =NAME=

Cuerpo del tema

Hello :wave:

This is a test topic… Let’s see the placeholder form.

Your email: =NAME=-=COUNTRY=@example.com


  1. Cree el botón “Usar plantilla como nuevo tema” (en el ejemplo anterior, este es un enlace, puede convertirlo en un botón)

Haga un elemento [wrap] con este texto. Esto lo hace disponible para apuntarlo con CSS y estilizarlo. Lo agrego a continuación.

<a href="https://meta.discourse.org/new-topic?category==CATEGORY=&title=This is a topic created by =NAME=&body=Hello :wave:
&nbsp;
This is a test topic... Let's see the placeholder form.
\
Your email: =NAME=-=COUNTRY=@example.com">[wrap=template-button]Use template as new topic[/wrap]</a>

Estilizando [wrap=template-button]
algo como :arrow_down_small:

Common / CSS

[data-wrap="template-button"] {
  background: var(--tertiary);
  color: var(--secondary);
  border-radius: var(--d-button-border-radius);
  padding: 0.5em 0.65em;
  transition: background 0.25s;
  &:focus,
  &:hover {
    background: var(--tertiary-hover);
    color: var(--secondary);
  }
}

El botón de plantilla se verá así :arrow_down_small:

template-button


Demo

Use template as new topic


Espero que este pequeño tutorial ayude a alguien que necesite algo similar :slightly_smiling_face:

Editar: He configurado un selector de categorías que agrega la capacidad de crear temas en diferentes categorías.


Ver la versión sin formato de esta publicación…

8 Me gusta

Eso es increíble Don, gracias. Esto en realidad se adapta muy bien a una de mis necesidades :slight_smile:

2 Me gusta

Algo a tener en cuenta es que los bloques de código a veces causan problemas:

usermod -aG sudo =USERNAME=

En este caso, highlight.js asume que esto es Java y convierte el bloque de código a:


<code>
  usermod -
  <span class="hljs-type">aG</span> 
  <span class="hljs-variable">sudo</span> 
  <span class="hljs-operator">=</span>
  USERNAME=
</code>

Puedo arreglarlo indicando que en realidad es un comando de shell:

    ```shell
    usermod -aG sudo =USERNAME=
    ```

Eso da como resultado:

usermod -aG sudo =USERNAME=

Si todo lo demás falla, text evita que highlight.js interfiera con los marcadores de posición.

Una solución más general (que Meta Discourse debe estar usando) es cambiar la configuración default code lang de auto a plaintext o algo similar. :wink:


No es que importe mucho, pero usar java es una forma de evitar que el marcador de posición se expanda cuando quieres escribir sobre marcadores de posición.

1 me gusta

¿Puedes revisar el enlace de vista previa? Parece estar roto para mí.

1 me gusta

Esta es una característica increíble y puedo ver muchos usos para ella.
Sin embargo, en nuestra respuesta, ¿es posible ocultar el =(name)= hasta que el usuario comience a escribir en el cuadro de texto? Siento que los usuarios (especialmente los nuevos) pueden no comprender su propósito, o que parece un formato incorrecto.

Creo que he conseguido que uno funcione de nuevo (:dedos_cruzados: :sonrisa_ligera:)

https://discourse.theme-creator.io/theme/Discourse/placeholder-forms

También lo he añadido a try.discourse.org para que puedas jugar más con él. :pulgar_hacia_arriba:

1 me gusta

Quizás podrías introducir un valor predeterminado que se muestre en su lugar.

1 me gusta

¡Eso funcionó! ¡Gracias!

2 Me gusta

Esta solución alternativa ya no parece funcionar. ¿Existen otras opciones para combinar reply-template y placeholder-forms?

4 publicaciones se dividieron en un nuevo tema: Los enlaces no funcionan en los formularios de marcador de posición