Skip to content

Instantly share code, notes, and snippets.

@jonathonbyrdziak
Last active July 20, 2024 21:37
Show Gist options
  • Save jonathonbyrdziak/9350935ac131b775634a0aa3ee25739e to your computer and use it in GitHub Desktop.
Save jonathonbyrdziak/9350935ac131b775634a0aa3ee25739e to your computer and use it in GitHub Desktop.
<?php
/*
In my situation I wanted to be able to declare a modal popup from the controller
and have that popup be pushed into the scripts section of my template.
So I began working on a helper function that would do this for me.
Each of these methods I commented out, definitely work to render a livewire component. The problem I'm struggling with
is that each of these methods also reset the app('view') object
What I finally came up with seems to work for my situation.
*/
if (!function_exists('addJavascriptFile')) {
/**
* Add custom javascript file to the page
*
* @param string $file
*
* @return void
*/
function addJavascriptFile($file)
{
app('view')->startPush('scripts');
echo '<script src="' . asset($file) . '"></script>'.PHP_EOL;
app('view')->stopPush();
}
}
if (!function_exists('addCssFile')) {
/**
* Add custom CSS file to the page
*
* @param string $file
*
* @return void
*/
function addCssFile($file)
{
app('view')->startPush('styles');
echo '<link rel="stylesheet" href="' . asset($file) . '">'.PHP_EOL;
app('view')->stopPush();
}
}
if (!function_exists('addCustomSnippets')) {
/**
* Add multiple custom snippets to the head by name.
*
* @param array $customSnippets
*
* @return void
*/
function addCustomSnippets($customSnippets)
{
foreach ($customSnippets as $customSnippet) {
addCustomSnippet($customSnippet);
}
}
}
if (!function_exists('addCustomSnippet')) {
/**
* Add single custom snippet to the head by name.
*
* @param string $customSnippet
*
* @return void
*/
function addCustomSnippet($customSnippet)
{
app('view')->startPush('scripts');
echo $customSnippet.PHP_EOL;
app('view')->stopPush();
}
}
if (!function_exists('addLivewireComponent')) {
/**
* Add Livewire component to the script stack
*
* @param string $component
* @param array $params
*
* @return void
*/
function addLivewireComponent($component, $params = [])
{
$scripts = app('view')->yieldPushContent('scripts');
$html = \Livewire\Livewire::mount($component, $params);
app('view')->startPush('scripts');
echo $html.PHP_EOL;
echo $scripts.PHP_EOL;
app('view')->stopPush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment