Mostrar HTML personalizado no cabeçalho para membros de um 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 curtidas

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 curtida
<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 curtidas

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 curtidas

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

1 curtida

Olá,

Eu estava procurando algo semelhante, mas excluindo alguns grupos, então tentei com o ChatGPT, e a resposta foi:

Para criar um tema HTML no Discourse que acione um script excluindo grupos específicos, você precisará usar as opções de personalização de tema do Discourse junto com JavaScript para lidar com exclusões de grupo. O Discourse fornece api.getCurrentUser() para recuperar detalhes do usuário, incluindo seus grupos, o que pode ser útil para acionar condicionalmente seu script.

Aqui está um exemplo de como você pode implementar isso na seção </head> do seu tema ou componente:

<script type="text/discourse-plugin" version="0.8">
    api.onPageChange(() => {
        // Recupera os detalhes do usuário atual
        const currentUser = api.getCurrentUser();

        if (currentUser) {
            // Lista de nomes de grupos que você deseja excluir da execução do script
            const excludedGroups = ['group1', 'group2'];

            // Obtém os grupos do usuário
            const userGroups = currentUser.groups.map(group => group.name);

            // Verifica se o usuário pertence a algum grupo excluído
            const isExcluded = excludedGroups.some(group => userGroups.includes(group));

            if (!isExcluded) {
                // Sua lógica de script personalizada aqui
                console.log('Script está sendo executado para este usuário.');
                // Exemplo: acione qualquer lógica personalizada para usuários não excluídos
                // customScriptFunction();
            } else {
                console.log('Usuário está em um grupo excluído, script não executado.');
            }
        }
    });
</script>

Explicação:

  1. api.onPageChange(): Executa o script sempre que a página muda.
  2. api.getCurrentUser(): Busca os detalhes do usuário atualmente logado.
  3. excludedGroups: Liste os grupos que você deseja excluir.
  4. userGroups.includes(group): Verifica se o usuário pertence a algum grupo excluído.
  5. Execução condicional do script: O script só será executado se o usuário não fizer parte de nenhum grupo excluído.

Você pode substituir a customScriptFunction(); por qualquer script que precise executar. Me avise se precisar de mais algum ajuste!

Quer dizer, minha mente explodiu com isso :exploding_head:. Eu ainda não tentei, mas o código do ChatGPT está correto?