I have a use case where I would like to add the content from a custom user field next to my username in the post header:
not sure the best way to go about this?
very new to discourse and all its wonders
I have a use case where I would like to add the content from a custom user field next to my username in the post header:
not sure the best way to go about this?
very new to discourse and all its wonders
You can do a lot with the methods found in plugin-api.js.es6. To add content before or after the poster name widget, use the decorateWidget method. Use 'poster-name:after' as the name/type parameter.
Checking the result of the console.log statement from the following code will tell you what attributes are available:
<script type="text/discourse-plugin" version="0.8.27">
api.decorateWidget('poster-name:after', helper => {
console.log('attrs', helper.attrs);
});
</script>
What you’ll see is that custom user fields are not available. To get access to them, you need to add the name of the user custom field to the public user custom fields Site Setting. Finding the name of the field can be tricky. One way to find the name is to go to /admin/customize/user_fields.json and look at the JSON for the page. You’ll see something like this:
{
"user_fields": [
{
"id": 1,
"name": "Terms of Service",
"description": "<a href=\"http://localhost:3000/tos\">I have read the tos</a>",
"field_type": "confirm",
"editable": true,
"required": false,
"show_on_profile": false,
"show_on_user_card": false,
"position": 1
},
{
"id": 4,
"name": "city",
"description": "your city",
"field_type": "text",
"editable": true,
"required": true,
"show_on_profile": false,
"show_on_user_card": false,
"position": 3
}
]
}
You can get the name of the field by appending “user_field_” to the field’s ID. So the “city” field on my site has the name “user_field_4”. Add the name to the public user custom fields Site Setting so that it is available in helper.attrs.
The following code will add the city field after the poster-name widget for users who have set that custom field. The field is wrapped in <span class="poster-user-field"></span> tags, so it can be styled with CSS.
<script type="text/discourse-plugin" version="0.8.27">
api.decorateWidget('poster-name:after', helper => {
const attrs = helper.attrs;
if (attrs.userCustomFields && attrs.userCustomFields.user_field_4) {
return helper.h('span.poster-user-field', helper.attrs.userCustomFields.user_field_4);
}
});
</script>
Obrigado por esta explicação, é algo que eu também estava procurando. Eu diria que o que falta nesta explicação é como inserir o snippet de JavaScript e onde você o faz. É necessário criar um plugin separado para isso?
O código que postei acima, com a instrução console.log que retorna os atributos da postagem, destina-se a ser incluído em um tema ou componente de tema. Para uma visão geral do desenvolvimento de temas do Discourse, consulte Guia do desenvolvedor para Temas do Discourse. Para detalhes sobre o uso dos métodos da API de Plugin em um tema, em vez de um plugin, consulte https://meta.discourse.org/t/using-the-pluginapi-in-site-customizations/41281.
Alguém sabe como fazer isso via temas?
É exatamente isso que estou procurando.
Quero poder vê-lo exatamente como o LinkedIn faz (mostra o cargo):

Assim como nesta conversa aqui:
Olá a todos! Sou novo no Discourse e encontrei este tópico que parece EXATAMENTE o que estou tentando fazer. Tenho um campo personalizado que gostaria que fosse exibido logo após o Nome Completo de um usuário em uma postagem.
Não sou completamente inexperiente em criar plugins para outros aplicativos web que usei no passado, então acho que com paciência e tentativa e erro eu conseguiria descobrir como fazer um Componente de Tema ou algo semelhante funcionar. Estou no processo de passar pelo tutorial de Desenvolvimento de Temas agora.
EU ACHO que descobri o nome do campo a ser adicionado à configuração “campos personalizados públicos do usuário” (acho que o id é 2, então defini como user_field_2).
Fiz login no meu site Discourse e criei um novo Componente de Tema. Habilitei-o para todos os temas que tenho instalados. Fui em JS e copiei o código de cima (mudando user_field_4 para user_field_2). Não pareceu fazer nada, então tenho certeza que fiz algo errado. Existe algum outro lugar onde eu precisava colar isso? Ou estou completamente errado?
Sei que esta postagem é um tanto antiga, então o código pode estar desatualizado. Alguma possibilidade de alguém poder me ajudar? Farei o meu melhor para responder a quaisquer perguntas ou fornecer os detalhes necessários. OBRIGADO!
Você está correto de que este código está desatualizado porque substituímos o sistema de widgets. Aqui estão algumas informações sobre isso do ano passado: Upcoming post stream changes - How to prepare themes and plugins .
Ainda é possível fazer isso funcionar, mas você terá que usar um Glimmer Component. Poderia ser algo assim:
import Component from "@glimmer/component";
import { apiInitializer } from "discourse/lib/api";
class UserFieldBadge extends Component {
static shouldRender(args) {
return !!args.post?.user_custom_fields?.user_field_4;
}
<template>
<span class="poster-user-field">
{{@post.user_custom_fields.user_field_4}}
</span>
</template>
}
export default apiInitializer((api) => {
api.renderAfterWrapperOutlet("post-meta-data-poster-name", UserFieldBadge);
});
Lembre-se de que você precisará corresponder user_field_4 neste código ao campo real que deseja exibir.
Deixarei para outros modificarem isso para que possa mostrar TODOS os campos de usuário personalizados públicos. ![]()