Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
MkNodes
MkNodes

Get started

  • Installation
  • Why should I use MkNodes?
  • A quick node tour
  • Changelog

MkNavs

  • MkNavs
  • Populate MkPages from SUMMARY.md
    • Test nested
      • General
      • Markdown-Exec
    • Test Subnav
      • Subnav page 1
      • Subnav page 2
    • Test file
  • Populate MkPages from folder
    • markdown_exec
    • sub_1
  • Routing
    • Routed page
    • Routed
      • Deeply
        • Nested
          • Nested page
          • Nav
            • Routed section page
  • Context propagation

MkPages

  • MkPages
  • MkClassPage
  • MkCode
  • MkCode
  • MkModulePage
  • info
  • Setting the homepage
  • Adding to MkPages
  • Metadata
  • Templates
  • Resources

The nodes

  • The nodes
  • Markdown flavours
  • Base nodes
    • MkNode
    • MkText
    • MkHeader
    • MkCompactAdmonition
    • MkCritic
    • MkLink
    • MkKeys
    • MkProgressBar
    • MkSpeechBubble
    • MkTemplate
    • MkLlm
  • Image nodes
    • MkImage
    • MkImageCompare
    • MkImageSlideshow
    • MkBadge
    • MkIcon
    • MkMaterialBadge
    • MkBinaryImage
    • MkCard
  • Container nodes
    • MkBlockQuote
    • MkAdmonition
    • MkContainer
    • MkCode
    • MkList
    • MkTable
    • MkHtmlTable
    • MkDefinitionList
    • MkDetailsBlock
    • MkHtmlBlock
    • MkTabbedBlocks
    • MkTabbed
    • MkAnnotations
    • MkFootNotes
    • MkShowcase
    • MkTaskList
  • Presentation nodes
    • MkTreeView
    • MkReprRawRendered
    • MkDiagram
    • MkTimeline
  • Documentation nodes
    • MkClassDiagram
    • MkDocStrings
    • MkCommentedCode
    • MkConfigSetting
    • MkClassTable
    • MkModuleTable
    • MkCliDoc
  • About-the-project nodes
    • MkChangelog
    • MkCodeOfConduct
    • MkLicense
    • MkDependencyTable
    • MkInstallGuide
    • MkCommitConventions
    • MkDevTools
    • MkShields
    • MkMetadataBadges
    • MkPipDepTree
    • MkPyDeps
  • Special nodes
    • MkInclude
    • MkIFrame
    • MkCommandOutput

Templating

  • Templating
  • Jinja Namespace
    • PackageContext
    • ThemeContext
    • GitContext
    • GitHubContext
  • Utility filters
  • MkNode filters
  • Template engines

Site generator

  • Use cases
    • Creating a website via config
  • CLI
    • build
    • serve
    • generate
    • render
    • render-folder
  • Site generator
  • Configuration
  • Site engines
  • The build process

Core API

  • Core API
  • Navs and pages
  • Routing
  • MkNode
  • Theming
  • Build step
  • Rendering

Development

  • Dependencies
  • Development environment
  • Dev Tools
  • Code of conduct
  • Contributing
  • License
Back to top
View this page

MkLink¶

github Show source on GitHub

A simple Link (with optional icon and option to show up as a button).¶

Description

If no title is given, the URL is used as a title.

Example: Regular

Jinja

{{ "https://www.google.com" | MkLink("This is a link") }}

Python

MkLink('https://www.google.com', 'This is a link')

This is a link

[This is a link](https://www.google.com)
<p><a href="https://www.google.com">This is a link</a></p>
`This is a link <https://www.google.com>`_
[This is a link](https://www.google.com)

Example: Button

Jinja

{{ "https://www.google.com" | MkLink("Disguised as button.", as_button=True) }}

Python

MkLink('https://www.google.com', 'Disguised as button.', as_button=True)

Disguised as button.

[Disguised as button.](https://www.google.com)
<p><a href="https://www.google.com">Disguised as button.</a></p>
`Disguised as button. <https://www.google.com>`_
[Disguised as button.](https://www.google.com)

Example: Colored

Jinja

{{ "https://www.google.com" | MkLink("Colored.", as_button=True, primary_color=True) }}

Python

MkLink('https://www.google.com', 'Colored.', as_button=True, primary_color=True)

Colored.

[Colored.](https://www.google.com)
<p><a href="https://www.google.com">Colored.</a></p>
`Colored. <https://www.google.com>`_
[Colored.](https://www.google.com)

Example: With icon

Jinja

{{ "https://www.google.com" | MkLink("With icon.", icon="octicon:link-24") }}

Python

MkLink('https://www.google.com', 'With icon.', icon='octicon:link-24')

link-24 With icon.

[<img src="https://api.iconify.design/octicon/link-24.svg?height=16" alt="link-24"> With icon.](https://www.google.com)
<p><a href="https://www.google.com"><img src="https://api.iconify.design/octicon/link-24.svg?height=16" alt="link-24"> With icon.</a></p>
`With icon. <https://www.google.com>`_
[<img src="https://api.iconify.design/octicon/link-24.svg?height=16" alt="link-24"> With icon.](https://www.google.com)

Example: With tooltip

Jinja

{{ "https://www.google.com" | MkLink("With tooltip.", as_button=True) }}

Python

MkLink('https://www.google.com', 'With tooltip.', as_button=True)

With tooltip.

[With tooltip.](https://www.google.com)
<p><a href="https://www.google.com">With tooltip.</a></p>
`With tooltip. <https://www.google.com>`_
[With tooltip.](https://www.google.com)

class MkLink(mknode.MkNode)

Name

Children

Inherits

MkNode
mknodes.basenodes.mknode
Base class for everything which can be expressed as Markup.

  • MkContainerBase
  • MkCompactAdmonition
  • MkLink
  • MkText
  • MkHeader
  • MkKeys
  • MkDocStrings
  • MkIcon
  • MkImage
  • MkProgressBar
  • BaseBlock
  • …

  • object

graph TD
  922779809["mklink.MkLink"]
  1359323199["mknode.MkNode"]
  2751680898["builtins.object"]
  1359323199 --> 922779809
  2751680898 --> 1359323199
/home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mklink/metadata.toml¶
[metadata]
icon = "octicon:link-24"
name = "MkLink"

[examples.regular]
title = "Regular"
jinja = """
{{ "https://www.google.com" | MkLink("This is a link") }}
"""

[examples.button]
title = "Button"
jinja = """
{{ "https://www.google.com" | MkLink("Disguised as button.", as_button=True) }}
"""

[examples.colored]
title = "Colored"
jinja = """
{{ "https://www.google.com" | MkLink("Colored.", as_button=True, primary_color=True) }}
"""

[examples.with_icon]
title = "With icon"
jinja = """
{{ "https://www.google.com" | MkLink("With icon.", icon="octicon:link-24") }}
"""

[examples.with_tooltip]
title = "With tooltip"
jinja = """
{{ "https://www.google.com" | MkLink("With tooltip.", as_button=True) }}
"""
# [examples.to_page]
# title = "To Page"
# jinja = """
# {{ page.parent.index_page | MkLink("To page.") }}
# """

[output.markdown]
template = """
[{{ node.icon | add(suffix=" ") }}{{ node.get_title() }}]({{ node.get_url() }}{{ node.tooltip | add(prefix=" '", suffix="'")}})
"""

[output.rst]
template = """
`{{ node.get_title() }} <{{ node.get_url() }}>`_
"""
mknodes.basenodes.mklink.MkLink¶
 18class MkLink(mknode.MkNode):
 19    """A simple Link (with optional icon and option to show up as a button).
 20
 21    If no title is given, the URL is used as a title.
 22    """
 23
 24    ICON = "octicons/link-24"
 25    ATTR_LIST_SEPARATOR = ""
 26
 27    def __init__(
 28        self,
 29        target: linkprovider.LinkableType,
 30        title: str | None = None,
 31        *,
 32        tooltip: str | None = None,
 33        icon: str | None = None,
 34        as_button: bool = False,
 35        primary_color: bool = False,
 36        **kwargs: Any,
 37    ) -> None:
 38        """Constructor.
 39
 40        Args:
 41            target: Link target
 42            title: Title used for link
 43            tooltip: Tooltip for the link
 44            icon: Optional icon to be displayed in front of title
 45            as_button: Whether link should be rendered as button
 46            primary_color: If rendered as button, use primary color as background.
 47            kwargs: keyword arguments passed to parent
 48        """
 49        super().__init__(**kwargs)
 50        self.target = target
 51        self._title = title
 52        self.tooltip = tooltip
 53        self.as_button = as_button
 54        self.primary_color = primary_color
 55        self._icon = icon
 56        if as_button:
 57            self.add_css_class("md-button")
 58        if primary_color:
 59            self.add_css_class("md-button--primary")
 60
 61    @property
 62    def icon(self) -> str:
 63        return icons.get_emoji_slug(self._icon) if self._icon else ""
 64
 65    def get_url(self) -> str:
 66        if isinstance(self.target, str) and helpers.is_url(self.target):
 67            return self.target  # no project context needed
 68        return self.ctx.links.get_url(self.target)
 69
 70    def get_title(self) -> str:
 71        return self._title or self.get_url()
 72
 73    @classmethod
 74    def for_pydantic_playground(
 75        cls,
 76        files: Mapping[str, str] | list[types.ModuleType] | Sequence[str | os.PathLike[str]],
 77        title: str = "Open in Pydantic Playground",
 78        active_index: int = 0,
 79        **kwargs: Any,
 80    ) -> MkLink:
 81        """Create a link to Pydantic playground with pre-populated files.
 82
 83        Args:
 84            files: The files to include in the playground. Can be:
 85                    - A mapping of filenames to code content
 86                    - A list of modules
 87                    - A list of file paths
 88            title: The title of the link
 89            active_index: The index of the active file in the playground
 90            **kwargs: Additional keyword arguments to pass to the Pydantic playground
 91
 92        Returns:
 93            An MkLink instance pointing to the Pydantic playground
 94        """
 95        from urllib.parse import quote
 96
 97        match files:
 98            case Mapping():
 99                file_data: list[dict[str, Any]] = [
100                    {"name": name, "content": content} for name, content in files.items()
101                ]
102            case [types.ModuleType(), *_]:
103                file_data = [
104                    {"name": f"{mod.__name__}.py", "content": inspect.getsource(mod)}  # type: ignore
105                    for mod in files
106                ]
107            case [str() | os.PathLike(), *_]:
108                file_data = []
109                for path in files:
110                    file = to_upath(path)
111                    file_data.append({
112                        "name": file.name,
113                        "content": file.read_text("utf-8"),
114                    })
115            case _:
116                raise TypeError(files)
117
118        # Add activeIndex to first file
119        if file_data:
120            file_data[active_index]["activeIndex"] = 1
121
122        json_str = json.dumps(file_data)
123        encoded = quote(json_str)
124
125        url = f"https://pydantic.run/new?files={encoded}"
126        return cls(url, title, **kwargs)
127
128    def to_md_unprocessed(self) -> str:
129        prefix = f"{self.icon} " if self.icon else ""
130        tooltip = f" {self.tooltip!r}" if self.tooltip else ""
131        return f"[{prefix}{self.get_title()}]({self.get_url()}{tooltip})"
Page info
Code for this page
mknodes.manual.nodes_section.create_section_for_nodes¶
 93def create_section_for_nodes(
 94    nav: mk.MkNav,
 95    klasses: Sequence[type[mk.MkNode]],
 96) -> mk.MkTable:
 97    table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
 98    for kls in klasses:
 99        tpl = "classpage_custom.jinja"
100        page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
101        nav += page
102        if kls.STATUS:
103            page.metadata.status = kls.STATUS
104        elif kls.JS_FILES:
105            page.metadata.status = "js"
106        elif kls.CSS:
107            page.metadata.status = "css"
108        page.created_by = create_section_for_nodes
109        link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
110        extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
111        table.add_row((link, kls.__doc__, extensions))
112    return table
Resources
Resources(css=[],
          markdown_extensions={'admonition': {},
                               'pymdownx.details': {},
                               'pymdownx.highlight': {'anchor_linenums': True,
                                                      'line_spans': '__span',
                                                      'pygments_lang_class': True},
                               'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
                                                                           'format': <function fence_code_format at 0x7ff77e88b060>,
                                                                           'name': 'mermaid'}]},
                               'pymdownx.tabbed': {},
                               'tables': {}},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
  source_function: create_section_for_nodes
  source_line_no: 93
hide:
- toc
icon: octicons/link-24
title: MkLink
Next
MkKeys
Previous
MkCritic
Copyright © 2024 Philipp Temminghoff
Made with Sphinx and @pradyunsg's Furo
On this page
  • MkLink
    • A simple Link (with optional icon and option to show up as a button).