### Complete Component Example with Props and Defaults
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
A comprehensive component example including type declarations and default values for props like 'title', 'subtitle', and 'class'.
```django
{# components/card.html #}
---
props.types = {
'title': str,
'subtitle': Optional[str],
'class': str,
}
props.defaults = {
'subtitle': None,
'class': 'card',
}
---
{% if title %}
{{ title }}
{% endif %}
{% if subtitle %}
{{ subtitle }}
{% endif %}
{{ children }}
```
--------------------------------
### Component Usage Examples
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Illustrates various ways to use the example component, showing correct usage, missing required props, incorrect types, extra props, and optional props.
```django
{# All props correct - no errors #}
{% #Button label="Click me" %}
{# Missing required prop - error #}
{% #Button %}
{# Wrong type - error #}
{% #Button label=123 %}
{# Extra prop - error #}
{% #Button label="Click" extra="value" %}
{# Optional with correct type - no error #}
{% #Button label="Click" size="small" %}
```
--------------------------------
### Example Component with Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
A complete example of a component template with front matter defining prop types and defaults. It demonstrates how to use these props in the template's HTML.
```django
---
props.types = {
'label': str,
'variant': Literal['primary', 'secondary'],
'disabled': bool,
'size': Optional[Literal['small', 'large']],
}
props.defaults = {
'variant': 'primary',
'disabled': False,
}
---
```
--------------------------------
### Python Front Matter Syntax Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Illustrates the structure for Python front matter within a file, which must start at the beginning of the file and be enclosed by '---' delimiters. The content between the delimiters is highlighted as Python code.
```python
---
# Python code here
props.types = {'label': str}
---
```
--------------------------------
### ANSI Output Example Command
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
An example command to generate colored output in the terminal using Pygmentize with the Slippers lexer, demonstrating the visual highlighting of code elements.
```bash
$ pygmentize -l slippers -f terminal component.html
```
--------------------------------
### Install Slippers
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Install the Slippers package using pip and add it to your Django project's INSTALLED_APPS.
```bash
pip install slippers
```
```python
INSTALLED_APPS = [
'slippers',
]
```
--------------------------------
### List Type Hint Examples
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Provides examples of type hints for lists containing strings, integers, or dictionaries.
```python
# List of specific type
items: List[str]
items: List[int]
items: List[Dict[str, Any]]
```
--------------------------------
### Legacy Keyword Argument Syntax Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/template-parsing.md
Demonstrates the legacy `value as key` syntax for keyword arguments, which can be enabled with `support_legacy=True`.
```django
{% some_tag "Hello" as greeting %}
```
--------------------------------
### Install Slippers Pygments Lexer
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Installs the Slippers package, which includes the Pygments lexer, making it available for use.
```bash
pip install slippers
```
--------------------------------
### Front Matter Syntax Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Demonstrates the basic syntax for front matter in components, which includes Python code enclosed by '---' lines and is not rendered in the output.
```text
---
python_code_here
---
template_content
```
--------------------------------
### Sphinx Configuration for Slippers Lexer
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Shows how to configure Sphinx to use the Slippers lexer for documentation. The lexer is automatically available after installation.
```python
extensions = ['sphinx.ext.autodoc']
# The lexer is automatically available
```
--------------------------------
### Component Template Variables Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Illustrates how template variables like 'username', 'message', and 'children' are available within a component's template, along with an example of its usage.
```django
{# Component template #}
{% /Wrapper %}
```
--------------------------------
### Fix components.yaml for slippers.E001
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/errors.md
Example of a correctly structured components.yaml file to resolve the E001 error.
```yaml
# templates/components.yaml
components:
Button: "components/button.html"
```
--------------------------------
### SLIPPERS_TYPE_CHECKING_OUTPUT Literal Type Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Example of using Literal to define allowed string values for SLIPPERS_TYPE_CHECKING_OUTPUT.
```python
List[Literal["console", "overlay"]]
```
--------------------------------
### PropError Example: Missing Required Prop
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Shows how to instantiate a PropError for a missing required property.
```python
PropError(
error="missing",
name="label",
expected=str,
actual=None
)
```
--------------------------------
### Typing Components Best Practice
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Recommends always typing components, even simple ones, for clarity and maintainability. This example shows a basic string prop declaration.
```python
props.types = {
'label': str,
}
```
--------------------------------
### Modern Keyword Argument Syntax Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/template-parsing.md
Illustrates the recommended `key=value` syntax for passing keyword arguments in Django templates, supporting extended variable names.
```django
{% #Button label="Click" disabled %}
{% attrs type="text" aria-label="Search" %}
```
--------------------------------
### Pygmentize Terminal Output Commands
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Provides command-line examples for using Pygmentize with the Slippers lexer to highlight files in different formats, including terminal (ANSI colors), raw HTML, and LaTeX. Also shows how to list available formats.
```bash
# Highlight with ANSI terminal colors
pygmentize -l slippers -f terminal component.html
# Highlight with raw HTML output
pygmentize -l slippers -f html -o component.html component.html
# Highlight with LaTeX
pygmentize -l slippers -f latex -o component.tex component.html
# List available formats
pygmentize -L formatters
```
--------------------------------
### Providing Sensible Defaults Best Practice
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Encourages providing default values for props to simplify usage and handle common cases. Examples include strings, booleans, and empty collections.
```python
props.defaults = {
'variant': 'primary',
'disabled': False,
'class': '',
}
```
--------------------------------
### Documenting Complex Props Best Practice
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Suggests documenting complex props to explain their purpose and structure. This example uses a comment to describe a component configuration object.
```python
---
# Component configuration object
```
--------------------------------
### Example Usage of slippers_token_kwargs
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/template-parsing.md
Demonstrates parsing component attributes using `slippers_token_kwargs` and resolving the resulting filter expressions.
```python
from slippers.template import slippers_token_kwargs
from django.template import Parser, Context
parser = Parser([])
# Parse button component attributes
bits = [
'label="Click me"',
'variant="primary"',
'disabled=True',
'x-data="controller"',
]
kwargs = slippers_token_kwargs(bits, parser)
# Returns:
# {
# 'label': SlippersFilterExpression('label="Click me"', parser),
# 'variant': SlippersFilterExpression('variant="primary"', parser),
# 'disabled': SlippersFilterExpression('disabled=True', parser),
# 'x-data': SlippersFilterExpression('x-data="controller"', parser),
# }
# Evaluate filter expressions
context = Context({})
evaluated = {key: expr.resolve(context) for key, expr in kwargs.items()}
# Returns:
# {
# 'label': 'Click me',
# 'variant': 'primary',
```
--------------------------------
### PropError Example: Extra Prop
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Demonstrates creating a PropError for an undeclared or extra property.
```python
PropError(
error="extra",
name="unknown_prop",
expected=None,
actual=str
)
```
--------------------------------
### Example Usage of SlippersFilterExpression
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/template-parsing.md
Shows how to instantiate and use `SlippersFilterExpression` to parse various directive and attribute syntaxes.
```python
from slippers.template import SlippersFilterExpression
from django.template import Parser
parser = Parser([]) # Simplified example
# Parse Alpine.js directive
expr = SlippersFilterExpression("x-data='controller'", parser)
# Variable: "x-data", Constant value: "controller"
# Parse attribute with hyphen
expr = SlippersFilterExpression("aria-label", parser)
# Variable: "aria-label"
# Parse event handler with filter
expr = SlippersFilterExpression("@click|default:'handler'", parser)
# Variable: "@click", Filter: "default" with argument "handler"
```
--------------------------------
### Example Usage of render_error_html
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Demonstrates how to use the `render_error_html` function with a sample `PropError` list. The output is a script tag that populates `window.slippersPropErrors`.
```python
errors = [
PropError(
error="invalid",
name="age",
expected=int,
actual=str,
)
]
html = render_error_html(
errors=errors,
tag_name="Profile",
template_name="pages/profile.html",
lineno=42,
)
# html contains:
#
```
--------------------------------
### Setting Default Prop Values in Front Matter
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Example of assigning a dictionary to `props.defaults` to specify default values for component props.
```python
props.defaults = {
'prop_name': 'default_value',
'another_prop': None,
}
```
--------------------------------
### Preprocess and Define Component Context with Front Matter
Source: https://github.com/mixxorz/slippers/blob/main/docs/using-components.md
This example demonstrates using front matter to define component types, default values, and dynamically set props like 'items' and 'title_tag' using Python code.
```slippers
---
from my_app.constants.icons import icon_bars_3
props.types = {
'title_level': Optional[int],
}
props.defaults = {
'title_level': 3,
}
props['items'] = [
('Link 1', '/path1'),
('Link 2', '/path2'),
('Link 3', '/path3')
]
props['title_tag'] = f'h{props['title_level']}'
---
{% for name, href in items %}
{{ name }}
{% endfor %}
```
--------------------------------
### Card Layout Component Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
A flexible card component that can optionally display a title and contains a slot for content.
```django
---
props.types = {
'title': Optional[str],
}
---
{% if title %}
{{ title }}
{% endif %}
{{ children }}
```
```django
Usage:
{% #Card title="My Card" %}
Card content
{% /Card %}
```
--------------------------------
### PropError Example: Invalid Type
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Illustrates how to create a PropError instance for an invalid type mismatch.
```python
PropError(
error="invalid",
name="age",
expected=int,
actual=str
)
```
--------------------------------
### SlippersTemplateLexer Regex Patterns
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Illustrates example regex patterns used by the SlippersTemplateLexer for identifying template variables, component tags, and other syntax elements.
```python
# Template variable: {{ variable }}
(r"\{\{", Comment.Preproc, "var")
# Block component: {% #ComponentName %}
(
r"(\\{%)(-?\s*)(#)([a-zA-Z_]\w*)",
bygroups(Comment.Preproc, Text, Name.Tag, Name.Tag),
"block",
)
# Inline component (PascalCase): {% ComponentName %}
(
r"(\\{%)(-?\s*)([A-Z][a-zA-Z_]\w*)",
bygroups(Comment.Preproc, Text, Name.Tag),
"block",
)
```
--------------------------------
### MkDocs Markdown with Slippers Code Block
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Example of using a custom 'slippers' fence in Markdown files for MkDocs documentation.
```markdown
```slippers
---
props.types = {'label': str}
---
```
```
--------------------------------
### Iterate Over Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Get an iterator for all prop names, including both explicitly set attributes and default values.
```python
def __iter__(self)
```
--------------------------------
### Declaring Prop Types in Front Matter
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Example of assigning a dictionary to `props.types` to declare the expected data types for component props.
```python
props.types = {
'prop_name': type_object,
'another_prop': Optional[str],
}
```
--------------------------------
### Resolve Missing Required Prop Error
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/errors.md
Example of a component template requiring a 'label' prop and how to fix the usage by providing the prop.
```django
---
props.types = {
'label': str, # Required
}
---
```
```django
{# Button %}
```
```django
{% #Button label="Click me" %}Content{% /Button %}
```
```django
---
props.types = {
'label': Optional[str],
}
---
```
--------------------------------
### Union Type Example for Component Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Demonstrates using Union and Optional for defining component prop types, including string, integer, boolean, list, dict, and optional strings.
```python
props.types = {
'variant': Literal['primary', 'secondary'],
'count': Union[int, str],
'optional': Optional[str],
}
```
--------------------------------
### Get Prop Count
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Return the total number of unique props, combining attributes and defaults.
```python
def __len__(self) -> int
```
--------------------------------
### Block Component Usage
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Example of using a block component, indicated by the '#' prefix, which requires a closing tag and is used for components that contain child content.
```django
{% #ComponentName prop1="value" %}
Child content here
{% /ComponentName %}
```
--------------------------------
### Runtime Type Checking with typeguard
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Demonstrates how to use the typeguard library for runtime type validation. Use check_type to validate a value against an expected type and get_type_name to get a human-readable type name.
```python
from typeguard import check_type, get_type_name
# Check if value matches type
check_type("prop_name", value, expected_type)
# Get human-readable type name
type_string = get_type_name(type_object)
```
--------------------------------
### Component with Props Declaration
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Defines a component with expected props specified in Python front matter. This example declares a 'label' prop of type string.
```django
{# components/button.html #}
---
props.types = {
'label': str,
}
---
```
--------------------------------
### Form Input Component Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
A reusable form input component with configurable label, type, name, and required status. Includes default values for type and required.
```django
---
props.types = {
'label': str,
'type': str,
'name': str,
'required': bool,
}
props.defaults = {
'type': 'text',
'required': False,
}
---
```
```django
Usage:
{% Input label="Email" name="email" type="email" required=True %}
```
--------------------------------
### Inline Component Usage
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Example of using an inline component, which does not require a closing tag and is typically used for components without child content.
```django
{% ComponentName prop1="value" prop2="value" %}
```
--------------------------------
### Get Prop Value
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Retrieve a prop value by its key. Falls back to default values if the attribute is not found, and then to None.
```python
def __getitem__(self, key: str) -> Any
```
```python
props = Props(
attributes={"name": "John"},
types={"name": str, "age": int},
defaults={"age": 18}
)
props["name"] # "John"
props["age"] # 18
props["email"] # None
```
--------------------------------
### Button Variants Component Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
A button component that supports different variants (primary, secondary, danger) and a disabled state. Defaults to 'primary' variant and enabled state.
```django
---
props.types = {
'label': str,
'variant': Literal['primary', 'secondary', 'danger'],
'disabled': bool,
}
props.defaults = {
'variant': 'primary',
'disabled': False,
}
---
```
```django
Usage:
{% Button label="Delete" variant="danger" %}
{% Button label="Save" %}
```
--------------------------------
### Using a Menu Component with Dynamic Front Matter Props
Source: https://github.com/mixxorz/slippers/blob/main/docs/using-components.md
Illustrates how to use the 'Menu' component, which has its 'items' and 'title_tag' dynamically set via front matter. This example shows overriding the 'title_level' prop.
```slippers
{# Usage #}
{% Menu title_level=5 %}
{# Output #}
```
--------------------------------
### Nesting Components
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Example of nesting components. The parent component renders its children within its template. Ensure the child component is correctly registered or imported.
```django
{# components/card.html #}
{{ children }}
{# Usage #}
{% #Card %}
{% Button label="Click me" %}
{% /Card %}
```
--------------------------------
### Component with Default Prop Values
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Define default values for component props using `props.defaults`. This example sets a default 'size' prop to 'large'.
```django
---
props.types = {
'size': Literal['small', 'large'],
}
props.defaults = {
'size': 'large',
}
---
```
--------------------------------
### Component with Props Definition
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Define component properties using `props.types` to specify expected data types for props. This example defines a 'label' prop of type string.
```django
---
props.types = {'label': str}
---
```
--------------------------------
### PropError.error Literal Type Example
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Example of using Literal to define the allowed error types for PropError.error.
```python
Literal["invalid", "missing", "extra"]
```
--------------------------------
### List and Highlight with Pygments
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Demonstrates how to list available Pygments lexers to confirm the Slippers lexer is present and how to highlight a Slippers component file.
```bash
# List available lexers
pygmentize -L lexers | grep -i slippers
# Highlight a file
pygmentize -l slippers -f html -o component.html component.html
```
--------------------------------
### Define Default Props for a Button Component
Source: https://github.com/mixxorz/slippers/blob/main/docs/using-components.md
Use `props.defaults` in the front matter to set fallback values for component props. This example sets a default class for a button.
```slippers
---
props.defaults = {
'class': 'btn btn-primary'
}
---
```
--------------------------------
### Manual Component Registration in Python
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Illustrates manual registration of components in Python code using the `register_components` function, mapping component names to template file paths.
```python
from slippers.templatetags.slippers import register_components
register_components({
"Button": "components/button.html",
"Card": "components/card.html",
})
```
--------------------------------
### Dynamic Component Registration via YAML
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Shows how to register components dynamically by defining a `templates/components.yaml` file that maps component names to their template paths.
```yaml
components:
ComponentName: "path/to/component.html"
```
--------------------------------
### Initialize Props Class
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Instantiate the Props class with attributes, type hints, and default values.
```python
class Props(Mapping):
def __init__(
self,
attributes: Dict[str, Any],
types: Dict[str, type],
defaults: Dict[str, Any],
) -> None
```
--------------------------------
### Using Descriptive Prop Names Best Practice
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Advises using descriptive names for props to improve code readability. Contrasts good naming with less clear alternatives.
```python
# Good
props.types = {
'button_label': str,
'button_variant': Literal['primary', 'secondary'],
}
# Less clear
props.types = {
'l': str,
'v': Literal['primary', 'secondary'],
}
```
--------------------------------
### Module-Level Settings Instance
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Provides a convenient way to import and use the global settings object.
```python
from slippers.conf import settings
if settings.SLIPPERS_RUNTIME_TYPE_CHECKING:
# Type checking is enabled
```
--------------------------------
### Add Slippers to INSTALLED_APPS
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Integrate Slippers into your Django project by adding it to INSTALLED_APPS.
```python
# settings.py
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'slippers', # Add this
]
```
--------------------------------
### Pygments Entry Point Configuration
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Illustrates how to register the Slippers lexer as a Pygments entry point in the `pyproject.toml` file. This configuration makes the lexer automatically available to Pygments.
```toml
[project.entry-points."pygments.lexers"]
SlippersLexer = "pygments_slippers:SlippersLexer"
```
--------------------------------
### Python Syntax Highlighting in Front Matter
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Demonstrates the use of standard Python lexer for highlighting code within the front matter. This includes keywords, type hints, and assignments.
```python
# Keywords: def, class, import, from, etc.
from typing import List, Optional
# Type hints
props.types = {
'items': List[str],
'value': Optional[int],
}
# Assignments
props.defaults = {
'count': 0,
}
```
--------------------------------
### Register Components with YAML
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Define your component templates in a components.yaml file to register them with Slippers.
```yaml
components:
Button: "components/button.html"
Card: "components/card.html"
```
--------------------------------
### Sphinx reStructuredText with Slippers Code Block
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Example of using the 'slippers' code block directive in reStructuredText files for Sphinx documentation.
```rst
.. code-block:: slippers
---
props.types = {
'label': str,
'disabled': bool,
}
---
```
--------------------------------
### Using a Button Component with Default Props
Source: https://github.com/mixxorz/slippers/blob/main/docs/using-components.md
Demonstrates how to use a component that has default props defined. If no class is provided, the default 'btn btn-primary' is used. If a class is provided, it overrides the default.
```slippers
{# Usage #}
{% Button %}
{# Output #}
{# Usage #}
{% Button class="btn btn-secondary" %}
{# Output #}
```
--------------------------------
### Handle slippers.E001: Components File Not Found
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/errors.md
This error occurs when the components.yaml file is missing. Ensure the file exists in a template directory and that the directory is configured in TEMPLATES['DIRS'].
```bash
SystemCheckError: System check identified some issues:
WARNINGS:
slippers.E001: Slippers was unable to find a components.yaml file.
HINT: Make sure it's in a root template directory.
```
--------------------------------
### Props Class Initialization
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Initializes a new Props object with attributes, type hints, and default values.
```APIDOC
## Props Class
### `__init__`
Initializes a new Props object.
#### Parameters
- **attributes** (Dict[str, Any]) - Required - Component attributes passed at render time
- **types** (Dict[str, type]) - Required - Type hints for each prop
- **defaults** (Dict[str, Any]) - Required - Default values for props
```
--------------------------------
### Programmatic Component Tag Creation
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Demonstrates how to programmatically create Django template tags for components using `create_component_tag`, allowing custom tag names and prefixes.
```python
from slippers.templatetags.slippers import create_component_tag
from django.template import Library
register = Library()
do_button = create_component_tag("components/button.html")
register.tag("button", do_button)
register.tag("#button", do_button)
```
--------------------------------
### Front Matter Type Execution with typing Module
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Shows how the typing module is automatically imported and available when executing component front matter using Python's exec(). This allows for type annotations like List, Dict, Optional, etc.
```python
from typing import *
# Available in front matter:
# List, Dict, Optional, Union, Literal, etc.
```
--------------------------------
### Settings Class Definition
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Defines the structure for accessing Slippers configuration properties.
```python
class Settings:
@property
def SLIPPERS_RUNTIME_TYPE_CHECKING(self) -> bool
@property
def SLIPPERS_TYPE_CHECKING_OUTPUT(self) -> List[Literal["console", "overlay"]]
```
--------------------------------
### Defining Optional Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Illustrates how to define optional props using Optional type annotation or by providing a default value.
```python
props.types = {
'optional1': Optional[str], # Optional (type)
'optional2': str,
}
props.defaults = {
'optional2': 'default', # Optional (default)
}
```
--------------------------------
### Register Components with components.yaml
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Define component mappings in a components.yaml file within a template directory.
```yaml
# templates/components.yaml
components:
Button: "components/button.html"
Card: "components/card.html"
Avatar: "components/avatar.html"
```
--------------------------------
### Generate HTML with Pygments and Slippers Lexer
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Programmatically highlights Slippers code using Pygments, specifying the Slippers lexer and HTML formatter.
```python
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
code = """---
props.types = {'label': str}
---
"""
lexer = get_lexer_by_name("slippers")
formatter = HtmlFormatter()
result = highlight(code, lexer, formatter)
```
--------------------------------
### Parse Component Code for Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Create a Props instance by parsing Python code to extract type hints and default values. The code executes in an environment where 'props' is available for assignment.
```python
@classmethod
def from_string(cls, attributes: Dict[str, Any], code: str) -> "Props"
```
```python
code = ""
props.types = {
'name': str,
'age': int,
'email': Optional[str],
}
props.defaults = {
'age': 18,
}
""
props = Props.from_string(
attributes={"name": "John"},
code=code
)
props["name"] # "John"
props["age"] # 18 (default)
props["email"] # None
```
--------------------------------
### Component Output Assignment to Variable
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Shows how to capture the rendered output of a component into a template variable using the `as` keyword.
```django
{% Button label="Save" as save_button %}
{% #Card as my_card %}
Content
{% /Card %}
{{ save_button }}
{{ my_card }}
```
--------------------------------
### MkDocs Configuration for Slippers Lexer
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Configures MkDocs to use the Pygments super-fences extension to enable custom fences for the 'slippers' language.
```yaml
markdown_extensions:
- pymdownx.superfences:
custom_fences:
- name: slippers
class: slippers
format: !!python/name:pymdownx.superfences.fence_code_highlight
```
--------------------------------
### Django Template Engine Configuration
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Ensure Django's default template engine is configured correctly for Slippers.
```python
# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR / 'templates',
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
],
},
},
]
```
--------------------------------
### Component Front Matter Syntax
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Defines the syntax for component front matter, including type declarations and default values for props.
```APIDOC
## Component Front Matter
### Front Matter Syntax
```
---
props.types = {
'prop_name': type_expression,
...
}
props.defaults = {
'prop_name': default_value,
...
}
---
{# Template content #}
```
### Type Declarations
The `props.types` dictionary uses Python type expressions.
#### Built-in Types
```python
props.types = {
'name': str,
'count': int,
'price': float,
'active': bool,
'items': list,
'mapping': dict,
}
```
#### Generic Types (from `typing` module)
The `typing` module is automatically imported in front matter.
```python
from typing import *
props.types = {
'items': List[str],
'mapping': Dict[str, int],
'either': Union[str, int],
'optional': Optional[str],
'callback': Callable[[int], str],
'restricted': Literal['small', 'medium', 'large'],
}
```
#### Type Checking Behavior
- **Required**: A typed prop with no default is required
- **Optional**: A prop with `Optional[T]` or `Union[T, None]` is optional
- **Default**: A prop with a default value is optional, even if not `Optional`
### Example Component
```django
---
props.types = {
'label': str,
'variant': Literal['primary', 'secondary'],
'disabled': bool,
'size': Optional[Literal['small', 'large']],
}
props.defaults = {
'variant': 'primary',
'disabled': False,
}
---
```
### Component Usage
```django
{# All props correct - no errors #}
{% #Button label="Click me" %}
{# Missing required prop - error #}
{% #Button %}
{# Wrong type - error #}
{% #Button label=123 %}
{# Extra prop - error #}
{% #Button label="Click" extra="value" %}
{# Optional with correct type - no error #}
{% #Button label="Click" size="small" %}
```
```
--------------------------------
### Running Django System Checks
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Command to execute Django's system checks, including custom checks like the one for Slippers' components.yaml.
```bash
python manage.py check
```
--------------------------------
### Multiline Prop Type and Default Declarations
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Demonstrates declaring multiple prop types and default values using Python's `Literal`, `List`, `Dict`, and `Callable` for complex prop definitions.
```python
props.types = {
'label': str,
'size': Literal['small', 'medium', 'large'],
'items': List[str],
'handlers': Optional[Dict[str, Callable]],
}
props.defaults = {
'size': 'medium',
'items': [],
}
```
--------------------------------
### Context and RequestContext Django Imports
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Imports Django's standard Context and RequestContext classes.
```python
from django.template import Context, RequestContext
```
--------------------------------
### Component Composition with FormGroup
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Demonstrates composing multiple components to build a form. The FormGroup component requires 'label', 'type', and 'name' props. Ensure all necessary components are available in the scope.
```django
{# components/form-group.html #}
---
props.types = {
'label': str,
'type': str,
'name': str,
}
---
{# Usage #}
{% #Form %}
{% FormGroup label="Email" type="email" name="email" %}
{% FormGroup label="Password" type="password" name="password" %}
{% Button label="Submit" %}
{% /Form %}
```
--------------------------------
### Standard Django Variable Syntax
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/template-parsing.md
Illustrates the typical syntax for variable access and filtering in standard Django templates.
```django
{{ user }}
{{ user.name }}
{{ users.0 }}
{{ user.name|upper }}
```
--------------------------------
### Conditional Rendering with Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Demonstrates how to conditionally render elements based on prop values. Ensure 'show_subtitle' is defined in props.types and optionally has a default value.
```django
---
props.types = {
'show_subtitle': bool,
}
props.defaults = {
'show_subtitle': True,
}
---
{{ title }}
{% if show_subtitle %}
{{ subtitle }}
{% endif %}
```
--------------------------------
### Custom Django System Check
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
A custom Django system check to verify the presence of the components.yaml file. It provides a hint on where to place the file if it's missing.
```text
slippers.E001: Slippers was unable to find a components.yaml file.
Hint: Make sure it's in a root template directory.
```
--------------------------------
### Extended Slippers Variable Syntax
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/template-parsing.md
Demonstrates the extended variable syntax supported by Slippers, including hyphens, colons, and at-signs.
```django
{{ x-data }}
{{ x-bind:class }}
{{ @click }}
{{ aria-label }}
{{ v-on:change }}
```
--------------------------------
### Minimal Component Structure
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
A basic component that renders a button and uses the `children` variable to display its content.
```django
```
--------------------------------
### Iterating Over Props in a List
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Shows how to iterate over a list of items provided as a prop. The 'items' prop must be declared as a List[str].
```django
---
props.types = {
'items': List[str],
}
---
{% for item in items %}
{{ item }}
{% endfor %}
```
--------------------------------
### Dynamic Attributes with Alpine.js
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Integrate Slippers with Alpine.js by using the `attrs` tag to dynamically render attributes like `x-data`, `x-bind`, and `@click`.
```django
Content
```
```django
Usage:
{% with x_data='{ open: false }' x_bind:class='{ active: open }' %}
{# Content with Alpine binding #}
{% endwith %}
```
--------------------------------
### Using Complex Data Structures as Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Illustrates how to pass and use complex data structures like dictionaries for props. The 'config' prop is expected to be a Dict[str, Any]. Use the 'safe' filter for rendering HTML attributes.
```django
---
props.types = {
'config': Dict[str, Any],
}
---
Configuration: {{ config.key }}
```
--------------------------------
### Front Matter Python Environment
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Shows the Python objects and modules available within the front matter execution environment, including the 'props' object and standard typing modules.
```python
# Props object is available
props # The Props instance being populated
# Typing module is automatically imported
from typing import *
# Accessible types:
List, Dict, Optional, Union, Literal, Any, Callable, etc.
```
--------------------------------
### Props Class `from_string`
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Parses Python code to extract prop type hints and default values, creating a new Props instance.
```APIDOC
## Props Class
### `from_string`
Parse a component's Python code section to extract type hints and defaults.
#### Parameters
- **attributes** (Dict[str, Any]) - Required - Attributes passed to the component
- **code** (str) - Required - Python code from the component front matter
#### Returns
A new `Props` instance with types and defaults extracted from the code.
#### Raises
- **SyntaxError** - Code contains invalid Python
- **NameError** - Code references undefined names (other than `props`)
#### Description
This class method executes the provided Python code in a controlled environment where `props` is available. The code can assign to:
- `props.types`: Dictionary mapping property names to type objects
- `props.defaults`: Dictionary mapping property names to default values
#### Example
```python
code = """
props.types = {
'name': str,
'age': int,
'email': Optional[str],
}
props.defaults = {
'age': 18,
}
"""
props = Props.from_string(
attributes={"name": "John"},
code=code
)
props["name"] # "John"
props["age"] # 18 (default)
props["email"] # None
```
```
--------------------------------
### Enable Runtime Type Checking
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Configure SLIPPERS_RUNTIME_TYPE_CHECKING in Django settings. Follows DEBUG by default.
```python
# settings.py
# Explicitly enable type checking (even in production)
SLIPPERS_RUNTIME_TYPE_CHECKING = True
# Or explicitly disable it
SLIPPERS_RUNTIME_TYPE_CHECKING = False
# Or omit the setting and let it follow DEBUG
DEBUG = True # Type checking will be enabled
```
--------------------------------
### SafeString and mark_safe Django Imports
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Imports SafeString for HTML-safe strings and mark_safe for marking strings as safe from escaping.
```python
from django.utils.html import SafeString
from django.utils.safestring import mark_safe
```
--------------------------------
### Prism.js Language Definition for Slippers
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Shows a basic Prism.js language definition for Slippers, including patterns for comments, tags, and variables. This can be extended with additional patterns for full support.
```javascript
Prism.languages.slippers = {
'comment': /\{#.*?#\}/,
'tag': /\{%\.*?%\}/,
'variable': /\{\{.*?\}\}/,
// ... additional patterns
};
```
--------------------------------
### Configure Type Checking Output
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Control where Slippers type checking errors are displayed using `SLIPPERS_TYPE_CHECKING_OUTPUT`. Options include 'console' and 'overlay'.
```python
# Show in console only
SLIPPERS_TYPE_CHECKING_OUTPUT = ["console"]
# Show in overlay only
SLIPPERS_TYPE_CHECKING_OUTPUT = ["overlay"]
# Show in both (default)
SLIPPERS_TYPE_CHECKING_OUTPUT = ["console", "overlay"]
```
--------------------------------
### Configure Type Checking Output
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Set SLIPPERS_TYPE_CHECKING_OUTPUT to control where validation errors are displayed. Defaults to console and overlay.
```python
# settings.py
# Display errors in both console and overlay (default)
SLIPPERS_TYPE_CHECKING_OUTPUT = ["console", "overlay"]
# Only show errors in console
SLIPPERS_TYPE_CHECKING_OUTPUT = ["console"]
# Only show errors in overlay
SLIPPERS_TYPE_CHECKING_OUTPUT = ["overlay"]
# Disable all error output
SLIPPERS_TYPE_CHECKING_OUTPUT = []
```
--------------------------------
### SlippersConfig Class Definition
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
The AppConfig subclass for Slippers, responsible for initialization tasks.
```python
class SlippersConfig(AppConfig):
name = "slippers"
def ready(self):
# Registers component tags from components.yaml
# Registers system checks
# Sets up file watching for development
```
--------------------------------
### Props Class `__getitem__`
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Retrieves a prop value, prioritizing attributes, then defaults, and finally returning None if not found.
```APIDOC
## Props Class
### `__getitem__`
Get a prop value, falling back to defaults then None.
#### Parameters
- **key** (str) - Required - Property name
#### Returns
The attribute value if present, otherwise the default value, otherwise `None`.
#### Example
```python
props = Props(
attributes={"name": "John"},
types={"name": str, "age": int},
defaults={"age": 18}
)
props["name"] # "John"
props["age"] # 18
props["email"] # None
```
```
--------------------------------
### Front Matter Syntax for Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Defines the structure for component front matter, specifying `props.types` for type declarations and `props.defaults` for default values.
```django
---
props.types = {
'prop_name': type_expression,
...
}
props.defaults = {
'prop_name': default_value,
...
}
---
{# Template content #}
```
--------------------------------
### Render Block Component
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Render a block component by opening and closing the component tag, allowing for content to be placed inside.
```django
{% #Card title="My Card" %}
Content here
{% /Card %}
```
--------------------------------
### Supported Type Annotations for Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Lists the supported type annotations for props, including basic, generic, literal, and callable types.
```python
# Basic types
str, int, float, bool, list, dict, Any
# Generic types
List[T], Dict[K, V], Optional[T], Union[T, U]
# Literal types
Literal['value1', 'value2']
# Callable types
Callable[[ArgType], ReturnType]
```
--------------------------------
### Generic Type Declarations in Front Matter
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Illustrates the use of generic types from Python's `typing` module for prop declarations. Supports `List`, `Dict`, `Union`, `Optional`, `Callable`, and `Literal`.
```python
from typing import *
props.types = {
'items': List[str],
'mapping': Dict[str, int],
'either': Union[str, int],
'optional': Optional[str],
'callback': Callable[[int], str],
'restricted': Literal['small', 'medium', 'large'],
}
```
--------------------------------
### Map Values with match Filter
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Use the `match` template filter to map input values to corresponding output values based on a predefined set of key-value pairs.
```django
{{ size|match:"small:sm,medium:md,large:lg" }}
```
--------------------------------
### Capture Content with fragment
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Use the `fragment` template tag to capture a block of template content and assign it to a variable for later use.
```django
{% fragment as header %}
My Header
{% endfragment %}
{{ header }}
```
--------------------------------
### Assigning Variables to Component Context
Source: https://github.com/mixxorz/slippers/blob/main/docs/using-components.md
Shows how to assign a value to a variable within the component's context using `props['var_name'] = my_value`.
```python
props['var_name'] = my_value
```
--------------------------------
### Slippers Match Template Filter
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Use the `match` template filter provided by Slippers to map input values to specific output values based on a defined pattern.
```django
{{ color|match:"red:#ff0000,green:#00ff00,blue:#0000ff" }}
```
--------------------------------
### Component with Attributes
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Pass multiple attributes to a component, including boolean attributes and custom ones, to control its behavior and appearance.
```django
{% #Button
label="Submit"
variant="primary"
disabled=True
%}
```
--------------------------------
### Check Prop Types and Validate
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Validate component attributes against expected types and defaults. Flags missing required props, type mismatches, and extra props.
```python
def check_prop_types(
*,
attributes: Dict[str, Any],
types: Dict[str, type],
defaults: Dict[str, Any],
) -> List[PropError]
```
```python
errors = check_prop_types(
attributes={"name": "John", "extra": "value"},
types={
"name": str,
"age": Optional[int],
},
defaults={"age": 18}
)
# errors will contain:
# - PropError(error="extra", name="extra", ...)
```
--------------------------------
### Check Type Checking Output Modes
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/configuration.md
Verify which output modes (console, overlay) are enabled for type checking errors.
```python
from slippers.conf import settings
if "console" in settings.SLIPPERS_TYPE_CHECKING_OUTPUT:
# Console output is enabled
if "overlay" in settings.SLIPPERS_TYPE_CHECKING_OUTPUT:
# Overlay output is enabled
```
--------------------------------
### List and Dict Type Imports
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Imports List and Dict types from the typing module for generic collection type hinting.
```python
from typing import List, Dict
```
--------------------------------
### Fix TemplateSyntaxError: Var tag requires keyword arguments
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/errors.md
Illustrates the correct key=value syntax for the 'var' tag, which requires keyword arguments.
```django
{# Error: no arguments #}
{% var %}
{# Error: missing value #}
{% var foo %}
{# Error: legacy syntax not supported #}
{% var foo as bar %}
```
```django
{% var foo="value" %}
{% var foo=context_var bar="literal" %}
```
--------------------------------
### Enable/Disable Runtime Type Checking
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Configure runtime type checking for Slippers components by setting `SLIPPERS_RUNTIME_TYPE_CHECKING` in your Django settings.py.
```python
# settings.py
SLIPPERS_RUNTIME_TYPE_CHECKING = True # Enable
SLIPPERS_RUNTIME_TYPE_CHECKING = False # Disable
```
--------------------------------
### Defining Required Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
Shows how to declare a required prop. A prop is required if it has a type declaration, is not Optional, and has no default value.
```python
props.types = {
'required_prop': str, # Required
}
```
--------------------------------
### Dictionary Type Definitions
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Defines common dictionary types used for mappings and configurations. These are standard Python type hints.
```python
mapping: Dict[str, str]
config: Dict[str, Any]
```
--------------------------------
### Minimal Django Component
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/component-system.md
A basic component defined solely by its Django template. No front matter is required.
```django
{# components/button.html #}
```
--------------------------------
### Component with Optional Props
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/quick-reference.md
Define optional props using `typing.Optional` or by providing a default value. This component accepts an optional 'subtitle' prop.
```django
---
props.types = {
'label': str,
'subtitle': Optional[str],
}
---
{{ label }}
{% if subtitle %}
{{ subtitle }}
{% endif %}
```
--------------------------------
### Union and Optional Type Imports
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/types.md
Imports Union and Optional types from the typing module for creating complex type hints.
```python
from typing import Union, Optional
```
--------------------------------
### Set Prop Value
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/props.md
Assign a value to a prop, updating the attributes dictionary.
```python
def __setitem__(self, key: str, value: Any) -> None
```
```python
props["new_prop"] = "value"
```
--------------------------------
### SlippersLexer Class Definition
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/pygments-lexer.md
Defines the Pygments lexer for Slippers component files, specifying its name, aliases, and supported MIME types.
```python
class SlippersLexer(RegexLexer):
name = "Slippers"
aliases = ["slippers"]
mimetypes = ["application/x-slippers-templating"]
```
--------------------------------
### Basic attrs Tag Usage
Source: https://github.com/mixxorz/slippers/blob/main/_autodocs/api-reference/template-tags.md
Use the 'attrs' tag to render basic HTML attributes from context variables. Ensure the context contains the variables corresponding to the attribute names.
```django
```