如何在Shiny中使用Font Awesome的fas、far、fal、fab类型图标?
icon() Function Great question! I’ve run into this exact issue before when working with newer Font Awesome styles in Shiny. Here are a few straightforward ways to use fas, far, fal, and fab prefixes instead of the default fa:
Method 1: Directly Write HTML (No Dependencies)
If you want full control without relying on package updates or extra libraries, just use Shiny’s HTML() function to manually define the icon element. This works with any Shiny version:
# Solid style left arrow with pull-right class HTML('<i class="fas fa-angle-left pull-right"></i>') # Regular style user icon HTML('<i class="far fa-user"></i>') # Brand style GitHub icon HTML('<i class="fab fa-github"></i>')
This generates exactly the HTML you need—just swap out the prefix (fas/far/fal/fab) to match your desired style.
Method 2: Use Shiny's icon() Function (Cleaner Shiny Syntax)
If you prefer to stick with icon() instead of raw HTML, you can adjust the parameters to override the default fa prefix:
Submethod 2.1: Manual Class Override
Clear the default prefix parameter and specify the full class list directly:
icon("", prefix = "", class = "fas fa-angle-left pull-right")
- The first empty string skips the default icon name parsing
prefix = ""prevents Shiny from adding the defaultfa-prefix- The
classparameter includes your desired style prefix, icon class, and any extra classes (likepull-right)
Submethod 2.2: Use bslib (Recommended for Bootstrap 5+)
If you’re using Bootstrap 5 or later (via the bslib package), the icon() function gets a handy family parameter to specify Font Awesome styles directly. This is the cleanest approach:
- First install
bslibif you haven’t:install.packages("bslib") - Then use it in your app:
library(shiny) library(bslib) ui <- page_fluid( # Bootstrap 5 theme auto-includes modern Font Awesome theme = bs_theme(version = 5), # Solid left arrow with pull-right icon("angle-left", family = "fas", class = "pull-right"), # Regular user icon icon("user", family = "far"), # Brand Twitter icon icon("twitter", family = "fab") ) server <- function(input, output) {} shinyApp(ui, server)bslibhandles loading the correct Font Awesome version, so you don’t have to worry about CDN links or compatibility.
Quick Note on Font Awesome Versions
Keep in mind that fas/far/fal/fab are part of Font Awesome 5 and above. If you’re using an older Shiny setup without bslib, you’ll need to manually include the latest Font Awesome CSS in your UI:
tags$head( tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css") )
内容的提问来源于stack exchange,提问作者Márcio Mocellin




