Mostrar HTML personalizado en el encabezado para miembros de un grupo específico

Hello Discourse Fam! I’m hoping that there’s an easy solution for this! I feel like the answer is that I need to use some Javascript.

We have 4 buttons in the “after header” section of our admin CSS/HTML settings.

We would like to have some buttons only visible to members of specific groups, with the rest of the buttons visible to all users.

e.g. Let’s say we want those main 4 buttons for everyone, but we want another button to only be visible to the members of a particular GROUP.

I don’t know JS so if it’s really simple and someone could help provide a snippet or something, that would be so helpful :pray:

4 Me gusta

I found this article which seems very similar, for the Zendesk platform, but I think that’s the type of functionality we’re looking for!

1 me gusta
<div id="after-header">Stuff</div>
<script type="text/discourse-plugin" version="0.8">
    api.onPageChange(() => {
        let currentUser = api.getCurrentUser();
        var groups = currentUser.groups;
        const isInGroup1 = groups.some(g => g.name === 'group1');
        const isInGroup2 = groups.some(g => g.name === 'group2');
        const isInGroup3 = groups.some(g => g.name === 'group3');
        if (isInGroup1) { 
            $("#after-header").addClass("group1");
         }
        if (isInGroup2) { 
            $("#after-header").addClass("group2");
         }
        if (isInGroup3) { 
            $("#after-header").addClass("group3");
         }         
    });
</script>
.button-a,
.button-b {
    display: none;
}
#after-header.group1 .button-a {
    display: block
}
#after-header.group2 .button-b {
    display: block
}

It also seems to work if you replace
api.onPageChange(() => {
with
$( document ).ready(function() {
and then the script won’t load on every page, but I never know for sure where I need api.onPageChange(() => { .

5 Me gusta

If you install this component, all groups of the current user will be added as classes in the page body, making it easy for CSS only further changes.

https://github.com/discourse/discourse-groups-css-classes-in-body

7 Me gusta

haha, that was going to be the next thing I tried to figure out

1 me gusta

Hola,

He estado buscando algo similar, pero excluyendo algunos grupos, así que lo intenté con ChatGPT, y la respuesta fue:

Para crear un tema HTML en Discourse que active un script excluyendo grupos específicos, necesitarás usar las opciones de personalización de temas de Discourse junto con JavaScript para manejar las exclusiones de grupos. Discourse proporciona api.getCurrentUser() para recuperar los detalles del usuario, incluidos sus grupos, lo que puede ser útil para activar condicionalmente tu script.

Aquí tienes un ejemplo de cómo podrías implementar esto en la sección </head> de tu tema o componente:

<script type="text/discourse-plugin" version="0.8">
    api.onPageChange(() => {
        // Recuperar los detalles del usuario actual
        const currentUser = api.getCurrentUser();

        if (currentUser) {
            // Lista de nombres de grupos que deseas excluir de la ejecución del script
            const excludedGroups = ['group1', 'group2'];

            // Obtener los grupos del usuario
            const userGroups = currentUser.groups.map(group => group.name);

            // Comprobar si el usuario pertenece a algún grupo excluido
            const isExcluded = excludedGroups.some(group => userGroups.includes(group));

            if (!isExcluded) {
                // Tu lógica de script personalizada aquí
                console.log('El script se ejecuta para este usuario.');
                // Ejemplo: activar cualquier lógica personalizada para usuarios no excluidos
                // customScriptFunction();
            } else {
                console.log('El usuario está en un grupo excluido, el script no se ejecuta.');
            }
        }
    });
</script>

Explicación:

  1. api.onPageChange(): Ejecuta el script cada vez que cambia la página.
  2. api.getCurrentUser(): Obtiene los detalles del usuario actualmente conectado.
  3. excludedGroups: Enumera los grupos que deseas excluir.
  4. userGroups.includes(group): Comprueba si el usuario pertenece a algún grupo excluido.
  5. Ejecución condicional del script: El script solo se ejecutará si el usuario no forma parte de ningún grupo excluido.

Puedes reemplazar customScriptFunction(); con el script que necesites ejecutar. ¡Avísame si necesitas algún ajuste adicional!

Quiero decir, mi mente está completamente alucinada con esto :exploding_head:. Aún no lo he probado, pero ¿es correcto el código de ChatGPT?