Skip to content

Badge ​

短的狀態標籤。對應 PHP 的 app/Component/Badge/BadgeView.blade.php。

Rust ​

rust
use cg_component::{Badge, Color, Component, Size};

Badge::new("已付款").color(Color::Success).icon("check").render();
Badge::new("Draft").size(Size::Sm).rounded(false).render();
方法預設說明
Badge::new(label)—label 接 &str / String(跳脫)或 Html(原樣輸出)
.color(Color)Neutralcg-badge--{color}
.size(Size)Mdcg-badge--{size}
.icon(name 或 Icon)無字串會變成 Sm 的 Icon;也可以給設定好的 Icon
.rounded(bool)truecg-badge--rounded
.class(...) / .attribute(...) / .attributes(...)—見樣板函式與屬性

樣板 ​

jinja
{{ cg_badge("Draft", color="warning", icon="warning") }}
{{ cg_badge("新", size="sm", rounded=false, attrs={"class": "ml-2", "title": "最近 7 天"}) }}
參數值
label(第一個)文字;`
colorneutral primary success warning danger info
sizesm md lg
icon已註冊的 icon 名稱
roundedtrue / false
attrsmap,見樣板函式與屬性

輸出 ​

html
<span class="cg-badge cg-badge--success cg-badge--md cg-badge--rounded" data-component="badge">
    <svg class="cg-icon cg-icon--sm" data-component="icon" data-icon="check" viewBox="0 0 24 24" … aria-hidden="true">
        <path d="M5 12.5l4 4L19 6.5" />
    </svg>
    <span class="cg-badge__label">已付款</span>
</span>

(實際輸出沒有換行與縮排,這裡為了好讀排版過。)

  • 根節點的 class 順序:cg-badge、顏色、尺寸、cg-badge--rounded,接著是你加的 class。
  • icon 在 label 前面,是裝飾性的(aria-hidden="true"),文字由 label 提供。

搭配狀態 ​

Badge 本身沒有行為,但可以當成 data-state-* 的顯示器:

rust
Badge::new("0").color(Color::Info).attribute("data-state-text", "matchCount")

data-state-text 會換掉根節點的 textContent,連同 icon 與 cg-badge__label 一起換掉。要保留結構,把屬性放在 label 裡面的元素上:

rust
let count = Html::raw(r#"<span data-state-text="matchCount">0</span> 筆"#.to_owned());
Badge::new(count).color(Color::Info)

測試 ​

tests/php_parity.rs:badges_match_the_php_overview_snapshot(各種顏色、尺寸、icon)與 the_default_badge_matches_the_php_catalog_snapshot。