Skip to content

Laravel Blade Components: inline HTML elements wrapped with spaces  #34931

@bplace

Description

@bplace
  • Laravel Version: 8.11.2
  • PHP Version: 7.3.17-1 +ubuntu18.04.1+deb.sury.org+1
  • Database Driver & Version: MariaDB 10.5.6

Description:

I have a Blade component which generates an HMTL link element given a page id, which needs to work as an inline element :

View file

Lorem ipsum l'<x-front.link id="12">anchor text</a>, etc...

components/front/link.blade.php

<a href="{{ route('page', $id) }}" {{ $attributes }}>{{ $slot }}</a>

Resulting HTML

Lorem ipsum l' <a href="/page/12">anchor text</a> ,etc...

The issue here are the spaces around the generated link element. I did try to have some cleanup in the component class, without success:

App/View/Components/Front/Link.php

public function render()
    {
        return function (array $data) {
            $html = View::make('components.front.link', $data)->render();

            return trim(preg_replace("#^\s+<a#m", "<a", $html));
        };
    }

After digging into the code, I've found the following lines :

Illuminate\View\Compilers\ComponentTagCompiler

protected function componentString(string $component, array $attributes) {
    // ...
    return " @component('{$class}', '{$component}', [".$this->attributesToString($parameters, $escapeBound = false).'])
<?php $component->withAttributes(['.$this->attributesToString($attributes->all(), $escapeAttributes = $class !== DynamicComponent::class).']); ?>';
}

protected function compileClosingTags(string $value)
{
    return preg_replace("/<\/\s*x[-\:][\w\-\:\.]*\s*>/", ' @endcomponentClass ', $value);
}

These two methods add a space before @component and after @endcomponentClass. Removing them does not seem to break Laravel, but I'll ask over the official repository.

Steps To Reproduce:

  • Create a component $ php artisan make:component Link
  • Edit component blade file {{ $slot }} or just an empty file
  • Write Blade view : Lorem ipsum l'<x-link>ariane</x-link>, etc...
  • Render page with additional spaces : Lorem ipsum l' ariane , etc...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions