Perfect plugin for me ![]()
How can I change the background color of a solved topic on the main page ?
Like some nice green to show everyone that this topic has a solution !
Best,
J.
AI-generated summary
The discussion revolves around customizing the styling of “solved topics” in the main list. Jerome_Bouvard initially asked how to change the background color of a solved topic on the main page, but downey and sam mentioned that it’s not possible without adding a custom class.
sam provided a CSS solution to style the accepted answer on the topic page, but not the main list. alxsal and ggurbet requested support for changing the background color of solved topics on the main page. sam stated that it’s not currently supported, but it could be added in the future.
Johani provided a solution using the api.addPostClassesCallback method, which adds a topic-solution class to posts marked as the answer. This allows for styling of solved topics on the main list. loginerror also provided a workaround using JavaScript, but Johani’s solution is more straightforward and efficient.
The solution is a simple JavaScript code snippet that adds the topic-solution class to posts marked as the answer:
api.addPostClassesCallback((attrs) => {
if (attrs.accepted_answer) return ["topic-solution"];
});
This allows for styling of solved topics on the main list using CSS.
You should be able to do it by targetting the post class via CSS.
Are you talking about the main list of all topics? If so, I don’t think this is possible.
If it’s on the topic page itself, AFAIK this is not possible either, because the only change to the “question” (first post) is the insertion of a paragraph in the post. You can style the post of the accepted solution, though, with CSS.
If someone knows a way, please share it because I also spent some time trying to do this. ![]()
I never added support for that, but on the actual topic page you can easily change it with
.topic-post.accepted-answer .topic-body {
background-color: #E9FFE0;
}
Sorry for reviving this very old topic, but I had the exact same question :
Is changing the background color of solved topic on the main page now supported ?
We would like to make it more visible on topic lists / search results if a topic has an accepted answer or not.
No we do not yet decorate rows in the topic list with a .solved class. Not against adding this if we can do that with no performance impact.
Мне кажется, что в какой-то момент класс .accepted-answer был удалён из этого div. Можно ли вернуть его, чтобы мы могли стилизовать пост с принятым ответом иначе?
В другой теме @awesomerobot сказал, что этот класс был добавлен к цитате в первом посте. Но я не могу найти его для тела поста:
Да, в цитате первого сообщения она есть. Но я говорю о теле сообщения, которое содержит ответ.
Я согласен, что было бы полезно добавить класс для div.topic-body у решённого поста.
Я могу придумать такой обходной путь:
<script type="text/discourse-plugin" version="0.8.42">
api.onPageChange((url) => {
$('button.accepted').parents('div.topic-body:first').toggleClass('solved-post-container', true);
});
</script>
С некоторым CSS вроде:
.solved-post-container {
outline: 3px !important;
outline-color: var(--success) !important;
outline-style: solid !important;
}
Но, на мой взгляд, всё ещё требуется какая-то точка входа в действие решения, чтобы контур исчезал, когда пост перестает быть решённым (возможно, это крайний случай, но было бы неплохо его покрыть).
Наличие класса для тела решённого поста, думаю, решило бы проблему ![]()
TL;DR
Это добавит класс topic-solution к сообщениям, отмеченным как ответ.
api.addPostClassesCallback((attrs) => {
if (attrs.accepted_answer) return ["topic-solution"];
});
Классы, которые присваиваются сообщению, определяются здесь.
Нужный вам хук уже существует в самом конце этого файла… вот так.
Plugin-API предоставляет метод, позволяющий добавлять классы к сообщению на основе условия.
Суть метода в том, что он выполняет переданный обратный вызов и возвращает класс для добавления, если условие выполнено.
При срабатывании обратного вызова Discourse передаёт ему атрибуты сообщения. Поэтому, например, можно сделать вот так.
api.addPostClassesCallback((attrs) => {
console.log(attrs);
});
Если открыть консоль, вы увидите, что там выводятся атрибуты каждого сообщения.
Это лишь примеры; там есть и многое другое.
Вам повезло: когда сообщение помечается как решение, Discourse отслеживает это и добавляет соответствующую информацию в атрибуты сообщения. Свойство называется accepted_answer.
Таким образом, вам достаточно проверить, истинно ли это значение, и добавить свой класс, если оно истинно. Вот как это делается:
api.addPostClassesCallback((attrs) => {
if (attrs.accepted_answer) return ["topic-solution"];
});
Этого достаточно, чтобы переключать класс даже в том случае, если автор темы передумает и выберет другое решение. Класс будет удалён из старого ответа и добавлен к новому.
Отлично, большое спасибо! ![]()

