Skip to content

icons (5)

get_favicon

get_favicon(url: str, provider: Literal['google', 'duckduckgo', 'iconhorse', 'yandex', 'favicon_io', 'favicon_ninja'] = 'duckduckgo', size: int = 32)

Return a favicon URL for the given URL.

Example

Jinja call:

{{ 'example.com' | get_favicon }}
Result: https://icons.duckduckgo.com/ip3/example.com.ico

Example

Jinja call:

{{ 'example.com' | get_favicon(provider='google', size=64) }}
Result: https://www.google.com/s2/favicons?domain=example.com&sz=64

DocStrings

Parameters:

Name Type Description Default
url str

The URL to get the favicon for.

required
provider Literal['google', 'duckduckgo', 'iconhorse', 'yandex', 'favicon_io', 'favicon_ninja']

The provider to use for the favicon.

'duckduckgo'
size int

Size of the favicon in pixels (not supported by all providers)

32
Source code in src/jinjarope/iconfilters.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def get_favicon(
    url: str,
    provider: Literal[
        "google", "duckduckgo", "iconhorse", "yandex", "favicon_io", "favicon_ninja"
    ] = "duckduckgo",
    size: int = 32,
):
    """Return a favicon URL for the given URL.

    Args:
        url: The URL to get the favicon for.
        provider: The provider to use for the favicon.
        size: Size of the favicon in pixels (not supported by all providers)
    """
    from urllib.parse import urlparse

    # Parse the URL to get the domain
    domain = urlparse(url).netloc or url

    match provider:
        case "google":
            return f"https://www.google.com/s2/favicons?domain={domain}&sz={size}"
        case "duckduckgo":
            return f"https://icons.duckduckgo.com/ip3/{domain}.ico"
        case "iconhorse":
            return f"https://icon.horse/icon/{domain}?size={size}"
        case "yandex":
            # Yandex supports sizes: 16, 32, 76, 120, 180, 192, 256
            valid_sizes = [16, 32, 76, 120, 180, 192, 256]
            closest_size = min(valid_sizes, key=lambda x: abs(x - size))
            return f"https://favicon.yandex.net/favicon/{domain}?size={closest_size}"
        case "favicon_io":
            return f"https://favicon.io/favicon/{domain}"
        case "favicon_ninja":
            return f"https://favicon.ninja/icon?url={domain}&size={size}"
        case _:
            msg = f"Invalid provider: {provider}"
            raise ValueError(msg)

get_icon_svg

get_icon_svg(icon: str, color: str | None = None, height: str | int | None = None, width: str | int | None = None, flip: Optional[Literal['horizontal', 'vertical', 'horizontal,vertical']] = None, rotate: Optional[Literal['90', '180', '270', 90, 180, 270, '-90', 1, 2, 3]] = None, box: bool | None = None) -> str

Return svg for given pyconify icon key.

Required packages: pyconify

Example

Jinja call:

{{ 'mdi:file' | get_icon_svg }}
Result: <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="currentColor" d="M13 9V3.5L18.5 9M6 2c-1.11 0-2 .89-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z"/></svg>

Example

Jinja call:

{{ 'mdi:file' | get_icon_svg(color='#ff0000', height=32, width=32) }}
Result: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="#ff0000" d="M13 9V3.5L18.5 9M6 2c-1.11 0-2 .89-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z"/></svg>

Example

Jinja call:

{{ 'mdi:file' | get_icon_svg(flip='horizontal', rotate=90) }}
Result: <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><g transform="rotate(90 12 12) translate(24 0) scale(-1 1)"><path fill="currentColor" d="M13 9V3.5L18.5 9M6 2c-1.11 0-2 .89-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z"/></g></svg>

DocStrings

Parameters:

Name Type Description Default
icon str

Pyconify icon name

required
color str | None

Icon color. Replaces currentColor with specific color, resulting in icon with hardcoded palette.

None
height str | int | None

Icon height. If only one dimension is specified, such as height, other dimension will be automatically set to match it.

None
width str | int | None

Icon width. If only one dimension is specified, such as height, other dimension will be automatically set to match it.

None
flip Flip | None

Flip icon.

None
rotate Rotation | None

Rotate icon. If an integer is provided, it is assumed to be in degrees.

None
box bool | None

Adds an empty rectangle to SVG that matches the icon's viewBox. It is needed when importing SVG to various UI design tools that ignore viewBox. Those tools, such as Sketch, create layer groups that automatically resize to fit content. Icons usually have empty pixels around icon, so such software crops those empty pixels and icon's group ends up being smaller than actual icon, making it harder to align it in design.

None
Source code in src/jinjarope/iconfilters.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def get_icon_svg(
    icon: str,
    color: str | None = None,
    height: str | int | None = None,
    width: str | int | None = None,
    flip: Flip | None = None,
    rotate: Rotation | None = None,
    box: bool | None = None,
) -> str:
    """Return svg for given pyconify icon key.

    Key should look like "mdi:file"
    For compatibility, this method also supports compatibility for
    emoji-slugs (":material-file:") as well as material-paths ("material/file")

    If no icon group is supplied as part of the string, mdi is assumed as group.

    When passing a string with "|" delimiters, the returned string will contain multiple
    icons.

    Args:
        icon: Pyconify icon name
        color: Icon color. Replaces currentColor with specific color, resulting in icon
               with hardcoded palette.
        height: Icon height. If only one dimension is specified, such as height, other
                dimension will be automatically set to match it.
        width: Icon width. If only one dimension is specified, such as height, other
               dimension will be automatically set to match it.
        flip: Flip icon.
        rotate: Rotate icon. If an integer is provided, it is assumed to be in degrees.
        box: Adds an empty rectangle to SVG that matches the icon's viewBox. It is needed
            when importing SVG to various UI design tools that ignore viewBox. Those
            tools, such as Sketch, create layer groups that automatically resize to fit
            content. Icons usually have empty pixels around icon, so such software crops
            those empty pixels and icon's group ends up being smaller than actual icon,
            making it harder to align it in design.

    Example:
        ``` py
        get_icon_svg("file")  # implicit mdi group
        get_icon_svg("mdi:file")  # pyconify key
        get_icon_svg("material/file")  # Material-style path
        get_icon_svg(":material-file:")  # material-style emoji slug
        get_icon_svg("mdi:file|:material-file:")  # returns a string with two svgs
        ```
    """
    label = ""
    for splitted in icon.split("|"):
        key = get_pyconify_key(splitted)
        import pyconify

        label += pyconify.svg(
            key,
            color=color,
            height=height,
            width=width,
            flip=flip,
            rotate=rotate,
            box=box,
        ).decode()
    return label

get_path_ascii_icon

get_path_ascii_icon(path: 'str | os.PathLike[str]') -> 'str'

Get an ASCII icon for a given file path based on its type.

Example

Jinja call:

{{ "path/to/file.py" | get_path_ascii_icon }}
Result: 🐍

Example

Jinja call:

{{ "src/" | get_path_ascii_icon }}
Result: 📁

DocStrings

Parameters:

Name Type Description Default
path str | PathLike[str]

File path as string or Path object

required

Returns:

Type Description
str

ASCII icon representing the file type

Source code in src/jinjarope/iconfilters.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
def get_path_ascii_icon(path: str | os.PathLike[str]) -> str:
    """Get an ASCII icon for a given file path based on its type.

    Args:
        path: File path as string or Path object

    Returns:
        ASCII icon representing the file type
    """
    path_obj = upath.UPath(path)

    # Handle symbolic links
    if path_obj.is_symlink():
        return AsciiIcon.SYMLINK

    # Handle folders
    if path_obj.is_dir():
        return AsciiIcon.FOLDER

    # Handle hidden files (Unix-style)
    if path_obj.name.startswith("."):
        return AsciiIcon.HIDDEN

    # Get extension and return corresponding icon or default
    extension = path_obj.suffix.lower()
    name_lower = path_obj.name.lower()

    # Check full filename for special cases
    if name_lower in EXTENSION_MAP:
        return EXTENSION_MAP[name_lower]

    return EXTENSION_MAP.get(extension, AsciiIcon.FILE)

get_path_icon

get_path_icon(path: 'str | os.PathLike[str]') -> 'str'

Get the icon mapping for a given file path or directory.

Example

Jinja call:

{{ "path/to/file.py" | get_path_icon }}
Result: logos:python

Example

Jinja call:

{{ "path/to/file.py" | get_path_icon | get_icon_svg(color='#ff0000', height=32, width=32) }}
Result: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 256 255"><defs><linearGradient id="logosPython0" x1="12.959%" x2="79.639%" y1="12.039%" y2="78.201%"><stop offset="0%" stop-color="#387EB8"/><stop offset="100%" stop-color="#366994"/></linearGradient><linearGradient id="logosPython1" x1="19.128%" x2="90.742%" y1="20.579%" y2="88.429%"><stop offset="0%" stop-color="#FFE052"/><stop offset="100%" stop-color="#FFC331"/></linearGradient></defs><path fill="url(#logosPython0)" d="M126.916.072c-64.832 0-60.784 28.115-60.784 28.115l.072 29.128h61.868v8.745H41.631S.145 61.355.145 126.77c0 65.417 36.21 63.097 36.21 63.097h21.61v-30.356s-1.165-36.21 35.632-36.21h61.362s34.475.557 34.475-33.319V33.97S194.67.072 126.916.072M92.802 19.66a11.12 11.12 0 0 1 11.13 11.13a11.12 11.12 0 0 1-11.13 11.13a11.12 11.12 0 0 1-11.13-11.13a11.12 11.12 0 0 1 11.13-11.13"/><path fill="url(#logosPython1)" d="M128.757 254.126c64.832 0 60.784-28.115 60.784-28.115l-.072-29.127H127.6v-8.745h86.441s41.486 4.705 41.486-60.712c0-65.416-36.21-63.096-36.21-63.096h-21.61v30.355s1.165 36.21-35.632 36.21h-61.362s-34.475-.557-34.475 33.32v56.013s-5.235 33.897 62.518 33.897m34.114-19.586a11.12 11.12 0 0 1-11.13-11.13a11.12 11.12 0 0 1 11.13-11.131a11.12 11.12 0 0 1 11.13 11.13a11.12 11.12 0 0 1-11.13 11.13"/></svg>

DocStrings

Parameters:

Name Type Description Default
path str | PathLike[str]

Path to the file or directory

required

Returns:

Type Description
str

iconify icon slug

Source code in src/jinjarope/iconfilters.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def get_path_icon(path: str | os.PathLike[str]) -> str:
    """Get the icon mapping for a given file path or directory.

    Args:
        path: Path to the file or directory

    Returns:
        iconify icon slug
    """
    path_obj = upath.UPath(path)

    # Handle directories
    if path_obj.is_dir():
        return {"icon": "vscode-icons:default-folder", "color": "#90A4AE"}["icon"]

    # Special cases for specific filenames
    if path_obj.name.lower() in ICONIFY_ICONS:
        return ICONIFY_ICONS[path_obj.name.lower()]["icon"]

    # Handle files by extension
    extension = path_obj.suffix.lower().lstrip(".")
    return ICONIFY_ICONS.get(
        extension, {"icon": "vscode-icons:default-file", "color": "#000000"}
    )["icon"]

get_pyconify_key

get_pyconify_key(icon: str) -> str

Convert given string to a pyconify key.

Required packages: pyconify

Example

Jinja call:

{{ 'material/file' | get_pyconify_key }}
Result: mdi:file

Example

Jinja call:

{{ ':material-file:' | get_pyconify_key }}
Result: mdi:file

DocStrings

Parameters:

Name Type Description Default
icon str

The string which should be converted to a pyconify key.

required
Source code in src/jinjarope/iconfilters.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
def get_pyconify_key(icon: str) -> str:
    """Convert given string to a pyconify key.

    Converts the keys from MkDocs-Material ("material/sth" or ":material-sth:")
    to their pyconify equivalent.

    Args:
        icon: The string which should be converted to a pyconify key.
    """
    for k, v in icons.PYCONIFY_TO_PREFIXES.items():
        path = f"{v.replace('-', '/')}/"
        icon = icon.replace(path, f"{k}:")
        icon = icon.replace(f":{v}-", f"{k}:")
    icon = icon.strip(":")
    mapping = {k: v[0] for k, v in icons._get_collection_map().items()}
    for prefix in mapping:
        if icon.startswith(f"{prefix}-"):
            icon = icon.replace(f"{prefix}-", f"{prefix}:")
            break
    if (count := icon.count(":")) > 1:
        icon = icon.replace(":", "-", count - 1)
    if ":" not in icon:
        icon = f"mdi:{icon}"
    return icon