# 对于新创建的标签，分配随机样式

**URL:** https://meta.discourse.org/t/for-newly-created-labels-assign-a-random-style/316577
**Category:** Development
**Created:** [2024年七月16日 14:56 UTC](https://meta.discourse.org/t/for-newly-created-labels-assign-a-random-style/316577 "2024-07-16T14:56:39Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![sheng\_hualuo](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/sheng_hualuo/32/430359_2.png) [@sheng\_hualuo](https://meta.discourse.org/u/sheng_hualuo)
#### Post date: [2024年七月16日 14:56 UTC](https://meta.discourse.org/t/for-newly-created-labels-assign-a-random-style/316577/1 "2024-07-16T14:56:39Z")

</div>

我为标签创建了 6 个 CSS 类：tag-style-1、tag-style-2、tag-style-3、tag-style-4、tag-style-5、tag-style-6。我想在我创建新标签时，随机分配以上 6 个类中的一个给它，这样新创建的标签就会有不同的样式。我知道标签样式组件是可行的，但它需要手动添加，而不是随机分配！

---

<div class="post-metadata">

### Author: ![Alteras](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/alteras/32/179824_2.png) [@Alteras](https://meta.discourse.org/u/Alteras)
#### Post date: [2024年七月16日 18:39 UTC](https://meta.discourse.org/t/for-newly-created-labels-assign-a-random-style/316577/2 "2024-07-16T18:39:09Z")

</div>

不完全是随机的，也不是在创建标签时，但你可以做一些类似于 [Tag Icons](https://meta.discourse.org/t/tag-icons/109757) 组件的事情，并使用 `plugin-api` 中的 `replaceTagRenderer()` 来修改视图中标签的 HTML（参见 [https://github.com/isabella232/discourse-tag-icons/blob/master/common/header.html）。](https://github.com/isabella232/discourse-tag-icons/blob/master/common/header.html%EF%BC%89%E3%80%82)

一个像这样的函数将获取标签名，将标签名映射到 1-6 的数字（即，将字符串编码为基数 6 并取最后一位/应用模数），并将其添加到 HTML 字符串中。它不会是随机的，因为样式将由标签名决定，但它会为所有用户保持相同的样式。

原始的默认渲染标签函数在这里：

> <https://github.com/discourse/discourse/blob/7d729603b48b9187d7b9fdadd9f3594b3ac01c64/app/assets/javascripts/discourse/app/lib/render-tag.js#L13-L69>
