From 39bf3544d4064a528a85c21a9069a9cae364a6c1 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Tue, 3 Sep 2024 09:47:33 +0200 Subject: Adding upstream version 0.46. Signed-off-by: Daniel Baumann --- docs/content/guide/components.md | 348 +++++++++++++++++++++++++++++++++++++ docs/content/guide/css_and_js.md | 230 ++++++++++++++++++++++++ docs/content/guide/index.md | 196 +++++++++++++++++++++ docs/content/guide/integrations.md | 3 + docs/content/guide/motivation.md | 115 ++++++++++++ docs/content/guide/performance.md | 3 + docs/content/guide/slots.md | 175 +++++++++++++++++++ 7 files changed, 1070 insertions(+) create mode 100644 docs/content/guide/components.md create mode 100644 docs/content/guide/css_and_js.md create mode 100644 docs/content/guide/index.md create mode 100644 docs/content/guide/integrations.md create mode 100644 docs/content/guide/motivation.md create mode 100644 docs/content/guide/performance.md create mode 100644 docs/content/guide/slots.md (limited to 'docs/content/guide') diff --git a/docs/content/guide/components.md b/docs/content/guide/components.md new file mode 100644 index 0000000..ac8a77f --- /dev/null +++ b/docs/content/guide/components.md @@ -0,0 +1,348 @@ +--- +title: Components +description: Declaring and using components. +--- + +
+
+ +## Declaring and Using Components + +The components are simple text files that look like regular Jinja templates, with three requirements: + +**First**, components must be placed inside a folder registered in the catalog or a subfolder of it. + +```python +catalog.add_folder("myapp/components") +``` + +You can call that folder whatever you want, not just "components". You can also add more than one folder: + +```python +catalog.add_folder("myapp/layouts") +catalog.add_folder("myapp/components") +``` + +If you end up having more than one component with the same name, the one in the first folder will take priority. + +**Second**, they must have a ".jinja" extension. This also helps code editors automatically select the correct language syntax to highlight. However, you can configure it in the catalog. + +**Third**, the component name must start with an uppercase letter. Why? This is how JinjaX differentiates a component from a regular HTML tag when using it. I recommend using PascalCase names, like Python classes. + +The name of the file (minus the extension) is also how you call the component. For example, if the file is "components/PersonForm.jinja": + +``` +└ myapp/ + ├── app.py + ├── components/ + └─ PersonForm.jinja +``` + +The name of the component is "PersonForm" and can be called like this: + +From Python code or a non-component template: + +- `catalog.render("PersonForm")` + +From another component: + +- ` some content `, or +- `` + +If the component is in a subfolder, the name of that folder becomes part of its name too: + +``` +└ myapp/ + ├── app.py + ├── components/ + └─ person + └─ PersonForm.jinja +``` + +A "components/person/PersonForm.jinja" component is named "person.PersonForm", meaning the name of the subfolder and the name of the file separated by a dot. This is the full name you use to call it: + +From Python code or a non-component template: + +- `catalog.render("person.PersonForm")` + +From another component: + +- ` some content `, or +- `` + +Notice how the folder name doesn't need to start with an uppercase if you don't want it to. + + + + + +## Taking Arguments + +More often than not, a component takes one or more arguments to render. Every argument must be declared at the beginning of the component with `{#def arg1, arg2, ... #}`. + +```html+jinja +{#def action, method="post", multipart=False #} + +
+ {{ content }} +
+``` + +In this example, the component takes three arguments: "action", "method", and "multipart". The last two have default values, so they are optional, but the first one doesn't. That means it must be passed a value when rendering the component. + +The syntax is exactly like how you declare the arguments of a Python function (in fact, it's parsed by the same code), so it can even include type comments, although they are not used by JinjaX (yet!). + +```python +{#def + data: dict[str, str], + method: str = "post", + multipart: bool = False +#} +... +``` + +## Passing Arguments + +There are two types of arguments: strings and expressions. + +### String + +Strings are passed like regular HTML attributes: + +```html+jinja +
...
+ + + + ... +``` + +### Expressions + +There are two different but equivalent ways to pass non-string arguments: + +"Jinja-like", where you use double curly braces instead of quotes: + +```html+jinja title="Jinja-like" + +``` + +... and "Vue-like", where you keep using quotes, but prefix the name of the attribute with a colon: + +```html+jinja title="Vue-like" + +``` + + + For `True` values, you can just use the name, like in HTML: +
+ ```html+jinja +
+ + + You can also use dashes when passing an argument, but they will be translated to underscores: +
+ ```html+jinja + + ``` +
+ ```html+jinja title="Example.jinja" + {#def aria_label = "" #} + ... + ``` +
+ +## With Content + +There is always an extra implicit argument: **the content** inside the component. Read more about it in the [next](/guide/slots) section. + +## Extra Arguments + +If you pass arguments not declared in a component, those are not discarded but rather collected in an `attrs` object. + +You then call `attrs.render()` to render the received arguments as HTML attributes. + +For example, this component: + +```html+jinja title="Card.jinja" +{#def title #} +
+

{{ title }}

+ {{ content }} +
+``` + +Called as: + +```html +bla +``` + +Will be rendered as: + +```html +
+

Products

+ bla +
+``` + +You can add or remove arguments before rendering them using the other methods of the `attrs` object. For example: + +```html+jinja +{#def title #} +{% do attrs.set(id="mycard") -%} + +
+

{{ title }}

+ {{ content }} +
+``` + +Or directly in the `attrs.render()` call: + +```html+jinja +{#def title #} + +
+

{{ title }}

+ {{ content }} +
+``` + + +The string values passed into components as attrs are not cast to `str` until the string representation is **actually** needed, for example when `attrs.render()` is invoked. + + +### `attrs` Methods + +#### `.render(name=value, ...)` + +Renders the attributes and properties as a string. + +Any arguments you use with this function are merged with the existing +attibutes/properties by the same rules as the `HTMLAttrs.set()` function: + +- Pass a name and a value to set an attribute (e.g. `type="text"`) +- Use `True` as a value to set a property (e.g. `disabled`) +- Use `False` to remove an attribute or property +- The existing attribute/property is overwritten **except** if it is `class`. + The new classes are appended to the old ones instead of replacing them. +- The underscores in the names will be translated automatically to dashes, + so `aria_selected` becomes the attribute `aria-selected`. + +To provide consistent output, the attributes and properties +are sorted by name and rendered like this: +` + `. + +```html+jinja + +``` +```html+jinja +
+ + +
+ +``` + + +Using `` to pass the extra arguments to other components **WILL NOT WORK**. That is because the components are translated to macros before the page render. + +You must pass them as the special argument `_attrs`. + +```html+jinja +{#--- WRONG 😵 ---#} + + +{#--- GOOD 👍 ---#} + + +``` + + +#### `.set(name=value, ...)` + +Sets an attribute or property + +- Pass a name and a value to set an attribute (e.g. `type="text"`) +- Use `True` as a value to set a property (e.g. `disabled`) +- Use `False` to remove an attribute or property +- If the attribute is "class", the new classes are appended to + the old ones (if not repeated) instead of replacing them. +- The underscores in the names will be translated automatically to dashes, + so `aria_selected` becomes the attribute `aria-selected`. + +```html+jinja title="Adding attributes/properties" +{% do attrs.set( + id="loremipsum", + disabled=True, + data_test="foobar", + class="m-2 p-4", +) %} +``` + +```html+jinja title="Removing attributes/properties" +{% do attrs.set( + title=False, + disabled=False, + data_test=False, + class=False, +) %} +``` + +#### `.setdefault(name=value, ...)` + +Adds an attribute, but only if it's not already present. + +The underscores in the names will be translated automatically to dashes, so `aria_selected` +becomes the attribute `aria-selected`. + +```html+jinja +{% do attrs.setdefault( + aria_label="Products" +) %} +``` + +#### `.add_class(name1, name2, ...)` + +Adds one or more classes to the list of classes, if not already present. + +```html+jinja +{% do attrs.add_class("hidden") %} +{% do attrs.add_class("active", "animated") %} +``` + +#### `.remove_class(name1, name2, ...)` + +Removes one or more classes from the list of classes. + +```html+jinja +{% do attrs.remove_class("hidden") %} +{% do attrs.remove_class("active", "animated") %} +``` + +#### `.get(name, default=None)` + +Returns the value of the attribute or property, +or the default value if it doesn't exist. + +```html+jinja +{%- set role = attrs.get("role", "tab") %} +``` + +... \ No newline at end of file diff --git a/docs/content/guide/css_and_js.md b/docs/content/guide/css_and_js.md new file mode 100644 index 0000000..8e296e2 --- /dev/null +++ b/docs/content/guide/css_and_js.md @@ -0,0 +1,230 @@ +--- +title: Adding CSS and JS +description: Your components might need custom styles or custom JavaScript for many reasons. +--- + +
+Your components might need custom styles or custom JavaScript for many reasons. +
+Instead of using global stylesheet or script files, writing assets for each individual component has several advantages: + +- **Portability**: You can copy a component from one project to another, knowing it will keep working as expected. +- **Performance**: Only load the CSS and JS that you need on each page. Additionally, the browser will have already cached the assets of the components for other pages that use them. +- **Simple testing**: You can test the JS of a component independently from others. + +## Auto-loading assets + +JinjaX searches for `.css` and `.js` files with the same name as your component in the same folder and automatically adds them to the list of assets included on the page. For example, if your component is `components/common/Form.jinja`, both `components/common/Form.css` and `components/common/Form.js` will be added to the list, but only if those files exist. + +## Manually declaring assets + +In addition to auto-loading assets, the CSS and/or JS of a component can be declared in the metadata header with `{#css ... #}` and `{#js ... #}`. + +```html +{#css lorem.css, ipsum.css #} +{#js foo.js, bar.js #} +``` + +- The file paths must be relative to the root of your components catalog (e.g., `components/form.js`) or absolute (e.g., `http://example.com/styles.css`). +- Multiple assets must be separated by commas. +- Only **one** `{#css ... #}` and **one** `{#js ... #}` tag is allowed per component at most, but both are optional. + +### Global assets + +The best practice is to store both CSS and JS files of the component within the same folder. Doing this has several advantages, including easier component reuse in other projects, improved code readability, and simplified debugging. + +However, there are instances when you may need to rely on global CSS or JS files, such as third-party libraries. In such cases, you can specify these dependencies in the component's metadata using URLs that start with either "/", "http://," or "https://." + +When you do this, JinjaX will render them as is, instead of prepending them with the component's prefix like it normally does. + +For example, this code: + +```html+jinja +{#css foo.css, bar.css, /static/bootstrap.min.css #} +{#js http://example.com/cdn/moment.js, bar.js #} + +{{ catalog.render_assets() }} +``` + +will be rendered as this HTML output: + +```html + + + + + +``` + +## Including assets in your pages + +The catalog will collect all CSS and JS file paths from the components used on a "page" render on the `catalog.collected_css` and `catalog.collected_js` lists. + +For example, after rendering this component: + +```html+jinja title="components/MyPage.jinja" +{#css mypage.css #} +{#js mypage.js #} + + + + +

Lizard

+

The Iguana is a type of lizard

+
+ + + +
+
+``` + +Assuming the `Card` and `Button` components declare CSS assets, this will be the state of the `collected_css` list: + +```py +catalog.collected_css +['mypage.css', 'card.css', 'button.css'] +``` + +You can add the `` and ` + + +``` + +## Middleware + +The tags above will not work if your application can't return the content of those files. Currently, it can't. + +For that reason, JinjaX includes WSGI middleware that will process those URLs if you add it to your application. + +```py +from flask import Flask +from jinjax import Catalog + +app = Flask(__name__) + +# Here we add the Flask Jinja globals, filters, etc., like `url_for()` +catalog = jinjax.Catalog(jinja_env=app.jinja_env) + +catalog.add_folder("myapp/components") + +app.wsgi_app = catalog.get_middleware( + app.wsgi_app, + autorefresh=app.debug, +) +``` + +The middleware uses the battle-tested [Whitenoise library](http://whitenoise.evans.io/) and will only respond to the *.css* and *.js* files inside the component(s) folder(s). You can configure it to also return files with other extensions. For example: + +```python +catalog.get_middleware(app, allowed_ext=[".css", .js", .svg", ".png"]) +``` + +Be aware that if you use this option, `get_middleware()` must be called **after** all folders are added. + +## Good practices + +### CSS Scoping + +The styles of your components will not be auto-scoped. This means the styles of a component can affect other components and likewise, it will be affected by global styles or the styles of other components. + +To protect yourself against that, *always* add a custom class to the root element(s) of your component and use it to scope the rest of the component styles. + +You can even use this syntax now supported by [all modern web browsers](https://caniuse.com/css-nesting): + +```sass +.Parent { + .foo { ... } + .bar { ... } +} +``` + +The code above will be interpreted as + +```css +.Parent .foo { ... } +.Parent .bar { ... } +``` + +Example: + +```html+jinja title="components/Card.jinja" +{#css card.css #} + +
+

My Card

+ ... +
+``` + +```sass title="components/card.css" +/* 🚫 DO NOT do this */ +h1 { font-size: 2em; } +h2 { font-size: 1.5em; } +a { color: blue; } + +/* 👍 DO THIS instead */ +.Card { + & h1 { font-size: 2em; } + & h2 { font-size: 1.5em; } + & a { color: blue; } +} + +/* 👍 Or this */ +.Card h1 { font-size: 2em; } +.Card h2 { font-size: 1.5em; } +.Card a { color: blue; } +``` + + +Always use a class **instead of** an `id`, or the component will not be usable more than once per page. + + +### JS events + +Your components might be inserted in the page on-the-fly, after the JavaScript files have been loaded and executed. So, attaching events to the elements on the page on load will not be enough: + +```js title="components/card.js" +// This will fail for any Card component inserted after page load +document.querySelectorAll('.Card button.share') + .forEach((node) => { + node.addEventListener("click", handleClick) + }) + +/* ... etc ... */ +``` + +A solution can be using event delegation: + +```js title="components/card.js" +// This will work for any Card component inserted after page load +document.addEventListener("click", (event) => { + if (event.target.matches(".Card button.share")) { + handleClick(event) + } +}) +``` diff --git a/docs/content/guide/index.md b/docs/content/guide/index.md new file mode 100644 index 0000000..0c092ea --- /dev/null +++ b/docs/content/guide/index.md @@ -0,0 +1,196 @@ +--- +title: Introduction +--- + +
+JinjaX is a Python library for creating reusable "components": encapsulated template snippets that can take arguments and render to HTML. They are similar to React or Vue components, but they render on the server side, not in the browser. +
+ +Unlike Jinja's `{% include "..." %}` or macros, JinjaX components integrate naturally with the rest of your template code. + +```html+jinja +
+ +

Products

+ {% for product in products %} + + {% endfor %} +
+
+``` + +## Features + +### Simple + +JinjaX components are simple Jinja templates. You use them as if they were HTML tags without having to import them: easy to use and easy to read. + +### Encapsulated + +They are independent of each other and can link to their own CSS and JS, so you can freely copy and paste components between applications. + +### Testable + +All components can be unit tested independently of the pages where they are used. + +### Composable + +A JinjaX component can wrap HTML code or other components with a natural syntax, as if they were another tag. + +### Modern + +They are a great complement to technologies like [TailwindCSS](https://tailwindcss.com/), [htmx](https://htmx.org/), or [Hotwire](https://hotwired.dev/). + +## Usage + +#### Install + +Install the library using `pip`. + +```bash +pip install jinjax +``` + +#### Components folder + +Then, create a folder that will contain your components, for example: + +``` +└ myapp/ + ├── app.py + ├── components/ 🆕 + │ └── Card.jinja 🆕 + ├── static/ + ├── templates/ + └── views/ +└─ requirements.txt +``` + +#### Catalog + +Finally, you must create a "catalog" of components in your app. This is the object that manages the components and their global settings. You then add the path of the folder with your components to the catalog: + +```python +from jinjax import Catalog + +catalog = Catalog() +catalog.add_folder("myapp/components") +``` + +#### Render + +You will use the catalog to render components from your views. + +```python +def myview(): + ... + return catalog.render( + "Page", + title="Lorem ipsum", + message="Hello", + ) +``` + +In this example, it is a component for the whole page, but you can also render smaller components, even from inside a regular Jinja template if you add the catalog as a global: + +```python +app.jinja_env.globals["catalog"] = catalog +``` + +```html+jinja +{% block content %} +
+ {{ catalog.irender("LikeButton", title="Like and subscribe!", post=post) }} +
+

Lorem ipsum

+{{ catalog.irender("CommentForm", post=post) }} +{% endblock %} +``` + +## How It Works + +JinjaX uses Jinja to render the component templates. In fact, it currently works as a pre-processor, replacing all: + +```html +content +``` + +with function calls like: + +```html+jinja +{% call catalog.irender("Component", attr="value") %}content{% endcall %} +``` + +These calls are evaluated at render time. Each call loads the source of the component file, parses it to extract the names of CSS/JS files, required and/or optional attributes, pre-processes the template (replacing components with function calls, as before), and finally renders the new template. + +### Reusing Jinja's Globals, Filters, and Tests + +You can add your own global variables and functions, filters, tests, and Jinja extensions when creating the catalog: + +```python +from jinjax import Catalog + +catalog = Catalog( + globals={ ... }, + filters={ ... }, + tests={ ... }, + extensions=[ ... ], +) +``` + +or afterward. + +```python +catalog.jinja_env.globals.update({ ... }) +catalog.jinja_env.filters.update({ ... }) +catalog.jinja_env.tests.update({ ... }) +catalog.jinja_env.extensions.extend([ ... ]) +``` + +The ["do" extension](https://jinja.palletsprojects.com/en/3.0.x/extensions/#expression-statement) is enabled by default, so you can write things like: + +```html+jinja +{% do attrs.set(class="btn", disabled=True) %} +``` + +### Reusing an Existing Jinja Environment + +You can also reuse an existing Jinja Environment, for example: + +#### Flask: + +```python +app = Flask(__name__) + +# Here we add the Flask Jinja globals, filters, etc., like `url_for()` +catalog = jinjax.Catalog(jinja_env=app.jinja_env) +``` + +#### Django: + +First, configure Jinja in `settings.py` and [jinja_env.py](https://docs.djangoproject.com/en/5.0/topics/templates/#django.template.backends.jinja2.Jinja2). + +To have a separate "components" folder for shared components and also have "components" subfolders at each Django app level: + +```python +import jinjax +from jinja2.loaders import FileSystemLoader + +def environment(loader: FileSystemLoader, **options): + env = Environment(loader=loader, **options) + + ... + + env.add_extension(jinjax.JinjaX) + catalog = jinjax.Catalog(jinja_env=env) + + catalog.add_folder("components") + for dir in loader.searchpath: + catalog.add_folder(os.path.join(dir, "components")) + + return env +``` + +#### FastAPI: + +TBD \ No newline at end of file diff --git a/docs/content/guide/integrations.md b/docs/content/guide/integrations.md new file mode 100644 index 0000000..0884d22 --- /dev/null +++ b/docs/content/guide/integrations.md @@ -0,0 +1,3 @@ +--- +title: Integrations +--- \ No newline at end of file diff --git a/docs/content/guide/motivation.md b/docs/content/guide/motivation.md new file mode 100644 index 0000000..90602b5 --- /dev/null +++ b/docs/content/guide/motivation.md @@ -0,0 +1,115 @@ +--- +title: Motivation +--- +
+An overview of what Jinja is about, and a glimpse into my disjointed decision-making process that got me here. +
+ +## Components are cool + +Despite the complexity of a single-page application, some programmers claim React or Vue offer a better development experience than traditional server-side rendered templates. I believe this is mostly because of the greatest improvement React introduced to web development: components. + + +Components, *as a way to organize template code*. Reactivity is cool too, but unrelated to the main issue. + + +When writing Python, we aim for the code to be easy to understand and test. However, we often forget all of that when writing templates that don't even meet basic standards: long methods, deep conditional nesting, and mysterious variables everywhere. + +Components are way cooler than the HTML soup tag of server-side rendered templates. They make it very clear what arguments they take and how they can render. More than anything, components are modular: markup, logic, and relevant styles all in one package. You can copy and paste them between projects, and you can share them with other people. + +This means a community has formed around sharing these components. Now you can easily find hundreds of ready-to-use components—some of them very polished—for every common UI widget, even the "complex" ones, like color-pickers. The big problem is that you can only use them with React (and Vue components with Vue, etc.) and in a single-page application. + +Jinja is about bringing that innovation back to server-side-rendered applications. + +## Not quite there: Jinja macros + +An underestimated feature of Jinja is *macros*. Jinja [macros](https://jinja.palletsprojects.com/en/3.0.x/templates/#macros) are template snippets that work like functions: They can have positional or keyword arguments, and when called return the rendered text inside. + +```html+jinja +{% macro input(name, value="", type="text", size=20) -%} + +{%- endmacro %} + +{% macro button(type="button") -%} + +{%- endmacro %} +``` + +You can then import the macro to your template to use it: + +```html+jinja +{% from 'forms.html' import input, button %} + +

{{ input("username") }}

+

{{ input("password", type="password") }}

+{% call button("submit") %}Submit{% endcall %} +``` +You must use the `{% call x %}` to pass the child content to the macro—by using the weird incantation `{{ caller() }}`—otherwise you can just call it like it were a function. + +So, can we use macros as components and call it a day? Well... no. This looks terrible: + +```html+jinja +{% call Card(label="Hello") %} + {% call MyButton(color="blue", shadowSize=2) %} + {{ Icon(name="ok") }} Click Me + {% endcall %} +{% endcall %} +``` + +compared to how you would write it with JSX: + +```html + + + Click Me + + +``` + +But macros are *almost* there. They would be a great foundation if we could adjust the syntax just a little. + +## Strong alternative: Mako + +At some point, I considered dropping this idea and switching to [Mako](https://www.makotemplates.org/), a template library by Michael Bayer (of SQLAlchemy fame). + +It's a hidden gem that doesn't get much attention because of network effects. See how close you can get with it: + +```html+mako +<%def name="layout()"> # <--- A "macro" +
+
+ ${caller.header()} +
+ + + +
+ ${caller.body()} +
+
+ + +## calls the layout def <--- Look! Python-style comments + +<%self:layout> + <%def name="header()"> # <--- This is like a "slot"! + I am the header + + <%def name="sidebar()"> +
    +
  • sidebar 1
  • +
  • sidebar 2
  • +
+ + this is the body + +``` + +Mako also has `<% include %>`s with arguments, which is another way of doing components if you don't need to pass content. + +However, in the end, the network effects, my familiarity with Jinja, and a little of not-invented-here syndrome tipped the scales to write a Jinja extension. diff --git a/docs/content/guide/performance.md b/docs/content/guide/performance.md new file mode 100644 index 0000000..609b952 --- /dev/null +++ b/docs/content/guide/performance.md @@ -0,0 +1,3 @@ +--- +title: Performance +--- diff --git a/docs/content/guide/slots.md b/docs/content/guide/slots.md new file mode 100644 index 0000000..991f327 --- /dev/null +++ b/docs/content/guide/slots.md @@ -0,0 +1,175 @@ +--- +title: Slots / Content +description: Working with content in components. +--- + +
+Besides attributes, components can also accept content to render inside them. +
+ +Everything between the open and close tags of the components will be rendered and passed to the component as an implicit `content` variable + +This is a very common pattern, and it is called a **_slot_**. A slot is a placeholder for content that can be provided by the user of the component. For example, we may have a `` component that supports usage like this: + +```html+jinja + +