0

I have a pagebuilder where i store {variable} in the database. When loaded on the frontend i want the variable to be translated to blade components.

$replacers = [
  'x-system-counters' => '<x-system-counters :data="$gloabal_variable"></x-system-counters>',
  'x-system-status' => '<x-system-status :data="$gloabal_variable"></x-system-status>',
];

$page = \App\Page::first();

$text = $page->content;
foreach ($replacers as $key => $value) {
    $text = str_replace('{'.$key.'}', $value, $text);
}

//Bladefile

{!! $text !!}

Any idea of how to solve this? I have tried the Blade::compileString($text) with no luck.

Thanks

2 Answers 2

3

After some digging, this was actually very easy. Laravel always delivers

$replacers = [
  'x-system-status' => view('compontents.system-status', $data)->toHtml(),
];

$page = \App\Page::first();

$text = $page->content;
foreach ($replacers as $key => $value) {
    $text = str_replace('{'.$key.'}', $value, $text);
}

Sign up to request clarification or add additional context in comments.

1 Comment

This works great but you have the pass the $data from the controller you are writing this into . So this will not pull the data from /app/view/components/.....
1

Basics

You can achieve this by following below steps:

  1. Create a template which can be dynamic(from db or anywhere) and then replace fixed variables from that template with values. I suppose $startpage->content is the dynamic template you're trying to compile.

  2. Replace variables with values using $startpage->content, then pass it to a simple blade with only one variable {!! $text !!}.

Solution

You can give any content you like to view function, view complies it and you can convert it to html and pass to everywhere you want.

Something like below code may help you:

$page = \App\Page::first();

$template = $startpage->content;

$desired_text = '<x-system-counters :data="$gloabal_variable"></x-system-counters>';

$text = preg_replace('/{{\$x_system_counters}}/', $desired_text, $$template)

$html = view('for_compile_view', compact('text'))->toHtml();

templates

your contents plus {{$x_system_counters}}

for_compile_view.blade.php

{!! $text !!}

3 Comments

Thanks for the effort, but that did't work at all. the blade components are not compiled. :(
Why? Please give more details of the errors and the results.
No errors, it's just not compiled. The element is listed in the html like this: <x-system-counters></x-system-counters> I use my loop instead of your preg_replace, becuase i have several of different components to load.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.