Heim Backend-Entwicklung PHP-Tutorial Bündeln Sie Ihre Symfony UX Twig-Komponenten

Bündeln Sie Ihre Symfony UX Twig-Komponenten

Jul 29, 2024 pm 05:46 PM

Have you heard about Symfony UX Twig Components? If not, I recommend starting by reading the official documentation to get firsthand understanding. However, in this article, I will give a brief introduction and then quickly jump to today's main topic: How to bundle Twig Components for reuse in your applications.

Bundling Your Symfony UX Twig Components

Symfony UX components are divided into two main categories: those consisting of a PHP class (controller) plus a Twig template (user interface) plus optional assets (JavaScript, CSS, etc.), which I will call "FullStack Components" in this article; and those made up solely of a user interface (Twig template and assets), referred to as "UI-only Components," also known as "Anonymous Twig Components."

FullStack components, thanks to their controller (the PHP class), can fetch information from a data source and render it on the user interface (the Twig template), making them incredibly dynamic tools. Think of them as compact, reusable controllers, each with a specific responsibility and UI. For example, a table of recommended products could be displayed both on your site's homepage and on individual product pages.

In contrast, the UI-only Components don't have a controller (the PHP class) and are useful when you need to reuse a user interface whose content is static or comes from an unknown data source. For example, a button with a label property or an alert message.

There are also other subcategories of UX components, such as "Live Components," and components whose UI is not rendered using a Twig template but is instead generated at runtime using pure PHP like UX Icon component. I won’t delve deeper into these components here, but you can find more information in the Symfony UX documentation.

Now let's get to the meat of the matter.

Bundling FullStack Components

Following the default recipe configuration, the twig_component extension includes a defaults config. This allows us (the bundles) to prepend new namespaces/paths and register our own FullStack components.

Here is an example of the structure you could follow to achieve this:

acme-bundle/
├── assets/
│   ├── dist/
│   │   ├── controller.js
│   │   └── style.min.css
│   └── package.json
├── src/
│   └── Twig/
│       └── Component/
│           └── Search.php
└── templates/
    └── components/
        └── Search.html.twig
Nach dem Login kopieren

The components/ directory is not mandatory for FullStack components; they can be placed at the root of the templates if your bundle focuses solely on UX components. However, it’s necessary for UI-only components. Therefore, I’ve placed both types under the same directory for consistency.

Here is the configuration you need to add to make the FullStack component work:

class AcmeBundle extends AbstractBundle
{
    public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        $builder->prependExtensionConfig('twig_component', [
            'defaults' => [
                'AcmeBundle\Twig\Component\\' => [
                    'template_directory' => '@Acme/components/',
                    'name_prefix' => 'Acme',
                ],
            ],
        ]);
    }

    // ...
}
Nach dem Login kopieren

Although the term defaults in the configuration might be a bit misleading (terms like mappings or namespaces might be clearer), this section allows you to register your own Twig components namespace and the necessary options to locate them.

Here's a trick: the template_directory isn't actually a directory path but rather a prefix for Twig template paths. It's unclear if this is intentional, but that's how it's used in the code. By taking advantage of this, I prefixed the path with the @Acme/ namespace. It worked perfectly!

Ensure the namespace you use matches the one assigned to your bundle by the TwigBundle. You can use the debug:twig command to find this out. If there's a mismatch, Twig won’t be able to locate your component templates.

For consistency, also use this namespace for the name_prefix option. If your Search.php component controller doesn't directly specify a component name, it will default to using this prefix. For instance, the component name would be Acme:Search by default.

If your UX component requires certain assets and your application uses an AssetMapper component, the simplest approach is to prepend the asset path:

class AcmeBundle extends AbstractBundle
{
    public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        $container->prependExtensionConfig('framework', [
            'asset_mapper' => [
                'paths' => [
                    __DIR__.'/../../assets/dist' => '@symfony/ux-acme-component',
                ],
            ],
        ]);
    }

    // ...
}
Nach dem Login kopieren

This will guarantee that your assets are imported correctly and associated with your component. And that wraps up everything about FullStack Twig Components!

From here, you can reuse your components across any application using either syntax:

<twig:Acme:Search></twig:Acme:Search>  

or  

{{ component('Acme:Search') }}
Nach dem Login kopieren

Bundling UI-only Components

Handling UI-only components is more complex because there is only one anonymous_template_directory. I believe we can improve this by allowing the registration of custom paths, similar to what we do with FullStack components. However, the term used here is misleading—it's not a directory path but a Twig template prefix. This prefix is used to concatenate and locate the template.

UI-only components follow a different convention from FullStack components, so they can't be located in the same way. Let’s look at an example to illustrate this:

<twig:Acme:Alert></twig:Acme:Alert>
Nach dem Login kopieren

Even if you store the Alert component in the /templates/components/ directory, you will encounter the following error:

Error rendering "Acme:Alert" component: Unknown component "Acme:Alert". And no matching anonymous component template was found.

The issue arises because the loading mechanism for UI-only components relies on the anonymous_template_directory configuration, which by default points to the templates/components/ directory in your application's path, not in the bundle path as you might expect. So, what can we do about this?

Behind the scenes, the component template finder service attempts to locate the template at templates/components/Acme/Alert.html.twig. Naturally, this template doesn't exist at the application location.

To address this issue, start by creating a new directory named Acme/ within the existing templates/components/ directory in your bundle. Then, place the Alert.html.twig template inside this new directory:

acme-bundle/
└── templates/
    └── components/
        ├── Acme/
        │   └── Alert.html.twig
        └── Search.html.twig
Nach dem Login kopieren

This adjustment partially resolves the issue. However, we still need to ensure that the loader searches within the bundle path. Fortunately, there is a Twig feature that can assist us with this.

In Twig, if a template name lacks a namespace, the loader will search all registered paths that don't specify a namespace. You can identify these paths by running the debug:twig command ((None) namespace).

So, how about registering unnamespaced Twig paths within your bundle's context? This trick lets Twig access the bundle's templates without needing a namespace. However, keep in mind this is more of a workaround to help the loader locate your bundle templates, specifically those under the templates/components/Acme/ directory:

final class AcmeBundle extends AbstractBundle
{
    public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        // ...

        $builder->prependExtensionConfig('twig', [
            'paths' => [
                'templates/bundles/AcmeBundle/' => null,
                dirname(__DIR__).'/templates/' => null,
            ],
        ]);
    }
}
Nach dem Login kopieren

Great! Now you can render your component. Just refresh the page, and it will display the component from /templates/components/Acme/Alert.html.twig.

Overriding Your Bundled UX Components

Sometimes, your generic UX components require UI tweaks. Consider a scenario where you're using a Bootstrap or Tailwind bundle that packages common UX components. Instead of creating entirely new components, including PHP controllers, you can simply override the Twig template (UI) by following the same TwigBundle convention.

The overriding rule works on a priority basis: the first template found takes precedence. That's why we registered the path 'templates/bundles/AcmeBundle/' => null at a high position in the prepend method.

Simply place your customized templates in templates/bundles/AcmeBundle/, following the same organization as the bundle, and the Twig loader will handle the rest, ensuring your modifications are used:

your-app/
└── templates/
    └── bundles/
        └── AcmeBundle/
            └── components/
                ├── Acme/
                │   └── Alert.html.twig
                └── Search.html.twig
Nach dem Login kopieren

Remember, components are designed to be reusable. Avoid creating a UX component unless you're sure it will be used at least twice. It's always better to refactor later, extract, and create a component when there's a real need for it.

Happy hacking! Cheers!

Das obige ist der detaillierte Inhalt vonBündeln Sie Ihre Symfony UX Twig-Komponenten. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heißer Artikel

<🎜>: Bubble Gum Simulator Infinity - So erhalten und verwenden Sie Royal Keys
4 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusionssystem, erklärt
4 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Flüstern des Hexenbaum
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen

Java-Tutorial
1671
14
PHP-Tutorial
1276
29
C#-Tutorial
1256
24
Erklären Sie sicheres Kennwort -Hashing in PHP (z. B. password_hash, password_verify). Warum nicht MD5 oder SHA1 verwenden? Erklären Sie sicheres Kennwort -Hashing in PHP (z. B. password_hash, password_verify). Warum nicht MD5 oder SHA1 verwenden? Apr 17, 2025 am 12:06 AM

In PHP sollten die Funktionen für Passwort_Hash und passwart_verify verwendet werden, um sicheres Passwort -Hashing zu implementieren, und MD5 oder SHA1 sollte nicht verwendet werden. 1) Passwort_hash generiert einen Hash, der Salzwerte enthält, um die Sicherheit zu verbessern. 2) Passwort_Verify prüfen Sie das Passwort und sicherstellen Sie die Sicherheit, indem Sie die Hash -Werte vergleichen. 3) MD5 und SHA1 sind anfällig und fehlen Salzwerte und sind nicht für die Sicherheit der modernen Passwort geeignet.

PHP und Python: Vergleich von zwei beliebten Programmiersprachen PHP und Python: Vergleich von zwei beliebten Programmiersprachen Apr 14, 2025 am 12:13 AM

PHP und Python haben jeweils ihre eigenen Vorteile und wählen nach den Projektanforderungen. 1.PHP ist für die Webentwicklung geeignet, insbesondere für die schnelle Entwicklung und Wartung von Websites. 2. Python eignet sich für Datenwissenschaft, maschinelles Lernen und künstliche Intelligenz mit prägnanter Syntax und für Anfänger.

PHP in Aktion: Beispiele und Anwendungen in realer Welt PHP in Aktion: Beispiele und Anwendungen in realer Welt Apr 14, 2025 am 12:19 AM

PHP wird in E-Commerce, Content Management Systems und API-Entwicklung häufig verwendet. 1) E-Commerce: Wird für die Einkaufswagenfunktion und Zahlungsabwicklung verwendet. 2) Content -Management -System: Wird für die Erzeugung der dynamischen Inhalte und die Benutzerverwaltung verwendet. 3) API -Entwicklung: Wird für die erholsame API -Entwicklung und die API -Sicherheit verwendet. Durch Leistungsoptimierung und Best Practices werden die Effizienz und Wartbarkeit von PHP -Anwendungen verbessert.

Wie funktioniert der Php -Typ -Hinweis, einschließlich Skalartypen, Rückgabetypen, Gewerkschaftstypen und nullbaren Typen? Wie funktioniert der Php -Typ -Hinweis, einschließlich Skalartypen, Rückgabetypen, Gewerkschaftstypen und nullbaren Typen? Apr 17, 2025 am 12:25 AM

PHP -Typ -Eingabeaufforderungen zur Verbesserung der Codequalität und der Lesbarkeit. 1) Tipps zum Skalartyp: Da Php7.0 in den Funktionsparametern wie int, float usw. angegeben werden dürfen. 3) Eingabeaufforderung für Gewerkschaftstyp: Da Php8.0 in Funktionsparametern oder Rückgabetypen angegeben werden dürfen. 4) Nullierstyp Eingabeaufforderung: Ermöglicht die Einbeziehung von Nullwerten und Handlungsfunktionen, die Nullwerte zurückgeben können.

Die dauerhafte Relevanz von PHP: Ist es noch am Leben? Die dauerhafte Relevanz von PHP: Ist es noch am Leben? Apr 14, 2025 am 12:12 AM

PHP ist immer noch dynamisch und nimmt immer noch eine wichtige Position im Bereich der modernen Programmierung ein. 1) Einfachheit und leistungsstarke Unterstützung von PHP machen es in der Webentwicklung weit verbreitet. 2) Seine Flexibilität und Stabilität machen es ausstehend bei der Behandlung von Webformularen, Datenbankoperationen und Dateiverarbeitung; 3) PHP entwickelt sich ständig weiter und optimiert, geeignet für Anfänger und erfahrene Entwickler.

PHP und Python: Verschiedene Paradigmen erklärt PHP und Python: Verschiedene Paradigmen erklärt Apr 18, 2025 am 12:26 AM

PHP ist hauptsächlich prozedurale Programmierung, unterstützt aber auch die objektorientierte Programmierung (OOP). Python unterstützt eine Vielzahl von Paradigmen, einschließlich OOP, funktionaler und prozeduraler Programmierung. PHP ist für die Webentwicklung geeignet, und Python eignet sich für eine Vielzahl von Anwendungen wie Datenanalyse und maschinelles Lernen.

Wie verhindern Sie die SQL -Injektion in PHP? (Vorbereitete Aussagen, PDO) Wie verhindern Sie die SQL -Injektion in PHP? (Vorbereitete Aussagen, PDO) Apr 15, 2025 am 12:15 AM

Die Verwendung von Vorverarbeitungsanweisungen und PDO in PHP kann SQL -Injektionsangriffe effektiv verhindern. 1) Verwenden Sie PDO, um eine Verbindung zur Datenbank herzustellen und den Fehlermodus festzulegen. 2) Erstellen Sie Vorverarbeitungsanweisungen über die Vorbereitungsmethode und übergeben Sie Daten mit Platzhaltern und führen Sie Methoden aus. 3) Abfrageergebnisse verarbeiten und die Sicherheit und Leistung des Codes sicherstellen.

PHP und Python: Code Beispiele und Vergleich PHP und Python: Code Beispiele und Vergleich Apr 15, 2025 am 12:07 AM

PHP und Python haben ihre eigenen Vor- und Nachteile, und die Wahl hängt von den Projektbedürfnissen und persönlichen Vorlieben ab. 1.PHP eignet sich für eine schnelle Entwicklung und Wartung großer Webanwendungen. 2. Python dominiert das Gebiet der Datenwissenschaft und des maschinellen Lernens.

See all articles