Изменить иконки глобально

Это простой способ глобально изменить иконку в Discourse.

  1. Щелкните правой кнопкой мыши на иконку, которую хотите изменить, и выберите «Посмотреть код» или «Исследовать» (в зависимости от браузера).

  2. Найдите имя иконки

  3. Найдите новую иконку здесь Find Icons with the Perfect Look & Feel | Font Awesome, например, external-link-alt

  4. Настройте и добавьте код на вкладке администрирование > настройка > темы > редактирование кода -> JS

// {theme}/javascripts/discourse/api-initializers/init-theme.gjs

import { apiInitializer } from "discourse/lib/api";

export default apiInitializer((api) => {
  api.replaceIcon("link", "external-link-tab");
});
  1. Иконки, которые не используются в Discourse по умолчанию, необходимо добавить в настройку сайта svg icon subset, а затем принудительно обновить браузер, чтобы изменения вступили в силу.
    Результат:
    image
    Все иконки «link» будут заменены на «external-link-tab».
    Если иконка используется для нескольких элементов на других страницах, например, для значков достижений (бейджей), она также будет заменена там.

Исключения

Обратите внимание, что уже существует компонент темы, позволяющий изменить иконку «Нравится». Я использую этот случай в качестве примера.

Иконка «heart» (сердечко), используемая для функции «Нравится», жестко запрограммирована с другими именами ('d-liked' и 'd-unliked') и должна обрабатываться иначе, чем другие иконки. Поэтому, чтобы заменить иконку :heart: на иконку :+1::

api.replaceIcon("d-liked", "thumbs-up");
api.replaceIcon("d-unliked", "thumbs-o-up");

like
firefox_2018-04-24_18-37-02
но на странице бейджей иконка остается «heart»:


поэтому, чтобы изменить ее на этой странице, добавьте:

api.replaceIcon("heart", "thumbs-up");

Другой пример:

api.replaceIcon("d-watching", "eye");

изменяет иконку «Отслеживание»:

Смотрите здесь другие исключения, покрывающие статус отслеживания, развертывание/сворачивание, уведомления и, конечно, лайки.
const REPLACEMENTS = {
  "d-tracking": "bell",
  "d-muted": "discourse-bell-slash",
  "d-regular": "far-bell",
  "d-watching": "discourse-bell-exclamation",
  "d-watching-first": "discourse-bell-one",
  "d-drop-expanded": "caret-down",
  "d-drop-collapsed": "caret-right",
  "d-unliked": "far-heart",
  "d-liked": "heart",
  "d-post-share": "link",
  "d-topic-share": "link",
  "notification.mentioned": "at",
  "notification.group_mentioned": "users",
  "notification.quoted": "quote-right",
  "notification.replied": "reply",
  "notification.posted": "reply",
  "notification.edited": "pencil-alt",
  "notification.bookmark_reminder": "discourse-bookmark-clock",
  "notification.liked": "heart",
  "notification.liked_2": "heart",
  "notification.liked_many": "heart",
  "notification.liked_consolidated": "heart",
  "notification.private_message": "far-envelope",
  "notification.invited_to_private_message": "far-envelope",
  "notification.invited_to_topic": "hand-point-right",
  "notification.invitee_accepted": "user",
  "notification.moved_post": "sign-out-alt",
  "notification.linked": "link",
  "notification.granted_badge": "certificate",
  "notification.topic_reminder": "far-clock",
  "notification.watching_first_post": "discourse-bell-one",
  "notification.group_message_summary": "users",
  "notification.post_approved": "check",
  "notification.membership_request_accepted": "user-plus",
  "notification.membership_request_consolidated": "users",
  "notification.reaction": "bell",
  "notification.votes_released": "plus",
  "notification.chat_quoted": "quote-right",
};

Ссылка: discourse/icon-library.ts at main · discourse/discourse (github.com)


Не стесняйтесь создавать другие компоненты тем и делиться ими в нашей категории Theme component!


Этот документ имеет контроль версий — предлагайте изменения на github.

38 лайков

Your post does help in changing icons globally but how to change the share icon in posts only? I do not want to change the link icon in the editor but, only in the posts. I checked the other posts in the forum but none of those work in the current build of Discourse, thus I am asking it here.

1 лайк

thanks for the clear guide. a small point:

is it possible to change d-watching to fas fa-eye and d-tracking to far fa-eye together?

if yes, how would one add the fas icon to the svg; as I tried adding fa-eye and this header:

<script type="text/discourse-plugin" version="0.8">
api.replaceIcon('d-watching', 'fa-eye');
api.replaceIcon('d-tracking', 'eye');
</script>

but the watching icon is not working.


also I was checking other icons such as bells, and I see even when I add bells to the svg icon subset it’s not loaded:

is there anything else I should do in order to be able to use bells?

Bells is a Pro icon, so it can’t be included, our default FA5 implementation only covers the free icons.

The solid eye icon is a bit of a special case: the FontAwesome 4 eye icon was moved to the regular bundle, so in Discourse we have a matcher for it that converts ‘eye’ to ‘far-eye’. Unfortunately, this stops you from using the solid ‘eye’ icon in Discourse, because Discourse will redirect eye to far-eye. If you absolutely must use that icon, you can copy the svg into a custom icon that you can rename to something of your liking, and add that to a theme or plugin.

3 лайка

thanks for the complete information :+1: , meanwhile I’ve tried several other icons, e.g. user-shield.

here is the header:
<script type="text/discourse-plugin" version="0.8">
api.replaceIcon('d-watching', 'fa-user-shield');
</script>

and I added fa-user-shield to the svg icon subset, but it still shows empty icon.

Try without the “fa-” prefix for user-shield (both in the JS code and the site setting).

still empty (tried with flag for easier snapshot):

That works locally for me. Did you refresh the page after making these changes?

yes, refreshed with F5 and ctrl+R just to be sure!

is there anyway to look for possible errors?

If you are familiar with the rails console, I would try logging in to the console and running SvgSprite.expire_cache and then refreshing the page to see if that does it.

2 лайка

How to change the solid (fas fa-bookmark) to regular version (far fa-bookmark)?

@dax Is there a way to change the default heart icon to an emoji icon?

1 лайк

Currently, no, you can only replace svg icons with other svg icons, not emojis.

4 лайка

Возможно ли использовать собственные добавляемые SVG-иконки вместо только иконок FA?

Да, подробности см. по адресу Introducing Font Awesome 5 and SVG icons.

2 лайка

Спасибо! Я также нашел Замена SVG-икон по умолчанию Discourse на пользовательские иконки в теме

В итоге я встроил SVG-спрайт напрямую в файл Header, так как загрузка и переименование, как описано в статье, у меня не сработали (хотя, возможно, это ошибка с моей стороны).

Итак, мой Header выглядит так:

<svg width="0" height="0" class="hidden" style="display: none;">
    <symbol id="myicon-search" ..... </symbol>  
    <!-- все мои символы здесь... -->
</svg>
<script type="text/discourse-plugin" version="0.8">
    api.replaceIcon('search', 'myicon-search'); 
</script>

И это легко поддерживать.

Я использую генератор SVG-спрайтов на https://svgsprit.es, чтобы убедиться, что формат правильный.

3 лайка

Можно ли использовать иконки Fabric от Microsoft с этим методом?

Да, вы должны быть в состоянии это сделать. Я не вижу официального распространения SVG-спрайтов этих иконок, но, согласно Where can I find the svg files of the icons? · Issue #1008 · OfficeDev/office-ui-fabric-core · GitHub, вы можете извлечь SVG самостоятельно, по одному, используя их имена.

4 лайка

Я пытаюсь сделать то же самое. Мне удалось успешно изменить иконку «поделиться» в сообщениях, но, похоже, это также меняет иконку ссылки в редакторе. Есть ли идеи, как изменить иконку только в сообщениях?

3 лайка

Есть ли способ глобально заменить иконку Font Awesome на SVG-иконку, загруженную в разделе загрузки темы? Я работаю над сайтом и хочу заменить иконку Font Awesome, которая отображается при решении темы (с использованием плагина discourse-solved), на логотип моего сайта. Мне сложно подойти к этому через код самого плагина, и я хотел узнать, работает ли метод заголовка для таких задач.