Giter Site home page Giter Site logo

log1x / sage-directives Goto Github PK

View Code? Open in Web Editor NEW
264.0 16.0 33.0 862 KB

A set of Blade directives for use with Roots Sage.

Home Page: https://log1x.github.io/sage-directives-docs/

License: MIT License

PHP 100.00%
wordpress sage roots-io blade blade-directives sage-directives

sage-directives's Introduction

Sage Directives

Latest Version Total Downloads Build Status

Sage Directives adds a variety of useful Blade directives for use with Sage 10 including directives for WordPress, ACF, and various miscellaneous helpers.

Requirements

Installation

Install via Composer:

$ composer require log1x/sage-directives

Build Documentation

$ yarn install
$ yarn run docs:build

Support

Bug Reports

If you discover a bug in Sage Directives, please open an issue.

Contributing

Contributing whether it be through PRs, reporting an issue, or suggesting an idea is encouraged and appreciated. When contributing code, please follow the existing directive format.

I work on Sage Directives entirely in my free time. If Sage Directives has helped you immensely and you would like to support me working on it in the future– feel free to leave a contribution using the ❤️ Sponsor button above.

License

Sage Directives is provided under the MIT License.

sage-directives's People

Contributors

alwaysblank avatar catgofire avatar czernika avatar dawidurbanski avatar dependabot[bot] avatar ekhaus avatar ethicka avatar jt-adwisemedia avatar kellymears avatar kevinblackdesk avatar lenardodb avatar log1x avatar markjaquith avatar noonanwebgroup avatar shanejones avatar themosaad avatar thomasbrunier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sage-directives's Issues

@date issue

Tried adding this, but just echos out '@Date('F j, Y')'

<time class="entry-time"> <span>@date('F j, Y')</span> <span itemprop="datePublished" content="@date('c')"></span> </time>
screenshot 2019-02-12 at 22 56 08

Get index @fields

Hi,

Is it possible to get the index of the loop with @fields? Something like:

<ul>
  @fields('list')
    <li>@sub('item') - @index </li>
  @endfields
</ul>

Sage directives not working properly in Sage 9.0.9 install

Hello,

I have Sage Directives working flawlessly in Sage 9.0.10 but I needed to downgrade to Sage 9.0.9 for a separate issue with Sage. Unfortunately, this seems to be incompatible with Sage Directives in its current 1.1 version.

I've installed it just the same as I did with all my other Sage 9.0.10 themes, but can't get it to operate.

Current Environment:

  • Sage 9.0.9
  • PHP 7.3.29
  • Composer 2.1.5

Are there any known issues tied to Sage 9.0.9?

Add $format_value parameter for @field and @sub

Hey @Log1x. Thanks for one more awesome plugin, I appreciate all of your hard work!

I have an idea related to @field and @sub directives.

Original ACF the_field(), the_sub_field() allows optional $format_value param, which I found extra useful, when

  • you need to disable data formatting for specific field when it's not needed,
  • you want to avoid disabling acf_the_content filter for that field or all fields.

Issue with @field and @sub directives

Default ACF Example: I'm using the wysiwyg field and I could disable formatting on its value by passing false as a third param:

the_field('headline', false, false); // $selector, $post_id, $format_value

But sage-directives use different params logic within an additional feature, which helps to add an array key as a second parameter. (I found it very useful too!).

@field('headline', false, false); // $selector, $key, $post_id

Possible solution

The only solution I can see there to follow existing directive format — add expression to check for fourth/third expression here https://github.com/Log1x/sage-directives/blob/master/src/Directives/ACF.php#L50-L61

So the actual full param structure might be:

  • $selector (mixed)
  • $key (string)
  • $post_id (int)
  • $format_value (boolean)

The directive call to disable formatting might look like:

@field('headline', false, false, false);

I think my suggested solution not super clean and it needs a few extra tricks at logic to check all combinations within an additional $key param. But I would like to hear any of your thoughts/ideas on this?

P.S.: with the @sub — everything the same, but excluding $post_id param.

Thanks!

Sage 10 usage

Dear @Log1x,
thank you very much for this! It is a very usefule addition to the sage theme.
However I am not sure how to integrate it with Sage 10. I added it via composer require Log1x / sage-directives and assumed that it is auto loaded via composer. But somehow the directives are not working. Is there a second step which I am missing?

Best regards,

Philipp

Using a !not directive

@if (have_posts()) becomes @posts
Love it.

Roots Sage's 404 uses @if ( ! have_posts())
Is there a ! not directive equivalent ?

[btw, great job with this project. thanks.]

Add @wpbodyopen

wp_body_open() should be used in themes after <body>. Would be nice for an @wpbodyopen directive.

Undefined function

/current/vendor/log1x/sage-directives/src/Directives.php

Know why I'd be getting undefined function error Call to undefined function App\Directives\collect() on line 36 ?

 public function __construct()
    {
        /**
         * Collect Directives into a flattened array.
         */
        $directives = collect($this->directives)
            ->flatMap(function ($directive) {
               if ($directive === 'ACF' && !function_exists('acf')) {
                    return;
                }
                return $this->get($directive);
            });

updating to accomodate laravel/helpers

Just noticed a minor update is needed to accommodate acorn pulling in the latest from Illuminate. Not sure if you have a preference for implementing or if the plan is to pull in laravel/helpers through acorn.

Thanks again for the great resources!

Missing PHP closing tag in @hasposts directive

I get the following error when using @hasposts and @endhasposts with a passed query e.g. @hasposts($query).

Uncaught Exception: syntax error, unexpected '<', expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF)

It appears there's a missing closing tag on the following line:

"<?php if (\$query->have_posts()) :";

When I directly edited the cached file I added ?> to the end of the line to fix the issue.

Uninitialized string offset

When i pass try to pass a post ID into the @field,
like
@field('text', 1)

I get this error "Uninitialized string offset".

It look like it try to render <?= get_field('text')[1]; ?>

Add the ability to pass arrays to Directives

Right now, since Blade casts anything passed to a directive as a string, everything currently passes through Util::parse() to explode the parameters it into a collection allowing the use of $expression->get(0), $expression->get(1), etc. which I more or less find to be the cleanest approach outside of using list() = explode().

Ideally, I'd like to figure out a way (regex?) to cast parameters passed as a short-handed array to an array without the current implementation of parse() breaking it due to exploding the colons.

Looking around online, it appears a common approach is to pass the expression through eval(), but for obvious reasons I am in no way interested in doing that.

If anybody has any ideas or would like to take a stab at this, it'd be greatly appreciated. It would help a lot in extending the usability/possibilities of various directives with them having so many parameters.

@field with Images can't declare size

When using the @field with an array image, as the third parameter is the ID, I didn't see anywhere in the documentation on how to declare sizes and image_size within the directive. Was there something I'm missing, or something not understood?

Can't get this to work - Sage 9.0.10

I ran composer 'require log1x/sage-directives' and then 'yarn install.' (inside my theme folder)
Also ran plain 'yarn' and 'yarn build'.
Note that 'yarn run docs:build' returns an error.

I do see the folder vendor/log1x/sage-directives and its contents.
I have uploaded that new folder to the server and tried out some directives but none of those are generating anything.

Example: @isnotnull($test) outputs just that exact text.

What do I need to check to make sure the sage-directives are correctly installed?
I feel like a step is missing...

Cannot use the attr parameter with the @thumbnail directive

Hello Brandon,

I'm trying to use the @thumbnail directive and to add a CSS class to my image using the 3rd argument from the get_the_post_thumbnail() function.

Not sure if it's intentional since you also use the last parameter to echo the image URL (as per your documentation), but it seems that you forget to send this 3rd parameter to the WP function here:

if (! empty($expression->get(2))) {
if ($expression->get(2) === 'false') {
return "<?= get_the_post_thumbnail_url({$expression->get(0)}, is_numeric({$expression->get(1)}) ? [{$expression->get(1)}, {$expression->get(1)}] : {$expression->get(1)}); ?>"; // phpcs:ignore
}
return "<?= get_the_post_thumbnail({$expression->get(0)}, is_numeric({$expression->get(1)}) ? [{$expression->get(1)}, {$expression->get(1)}] : {$expression->get(1)}); ?>"; // phpcs:ignore
}


PS.: Thanks for everything you're doing with Roots and your own sage and acf extensions.

@field inside @posts not working

Awesome plugin!
But i have one issue. I can't fetch my ACF field with @field
When using the get_field() function it's working as espected. Check code below.
Am i missing something?

@php
$query = new WP_Query([
'post_type' => 'product'
]);
@endphp

@posts($query)

Working: {{ get_field('config_button', get_post()) }}

Not working: @field('config_button', get_post())

Not working: @field('config_button')

@endposts

ACF Directives Not Rendering

I can't seem to get the ACF directives working?

My code:

@layouts('page_builder')
  {{{ get_the_title() }}}
@endlayouts

Renders:
Screen Shot 2019-04-10 at 9 48 29 AM

Other directives work fine.

Couldn't find a script named "docs:build".

Hello - setting this up on a fresh install, from within the local terminal. Install works fine, yarn build works fine. Error thrown on:

yarn run docs:build

Couldn't find a script named "docs:build".

Hopefully a simple workaround, but I've searched with no similar answers. Appreciate any help. Thanks!

`@instanceof` throws fatal error due to documentation example

This code:

@instanceof($latest_posts_query, 'WP_Query')
  {!! \App\pagination($latest_posts_query) !!}
@endinstanceof

Renders this code:

<?php if ($latest_posts_query instanceof 'WP_Query') : ?>
  <?php echo \App\pagination($latest_posts_query); ?>

<?php endif; ?>

With the error of Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: syntax error, unexpected ''WP_Query'' (T_CONSTANT_ENCAPSED_STRING).

The documentation of this directive suggests passing the class name as a string but in fact, should be the actual instance object.

Simply removing the quotes around the second argument will fix the issue.

Suggestion: the_post(), setup_postdata(), wp_reset_postdata() directives.

Hi. Great library!

It would be cool if you could add the_post() as a blade directive, like @post or @thepost.

so this default Sage template code:

@while(have_posts()) @php the_post() @endphp
  @include('partials.page-header')
  @include('partials.content-page')
@endwhile

Becomes:

@while(have_posts()) @thepost
  @include('partials.page-header')
  @include('partials.content-page')
@endwhile

It could be also useful to add directives for setup_postdata() and wp_reset_postdata().

It would help to avoid writing boilerplate code in controllers to pass custom queries results.
For example (as you already have @global()):

@global($post)
@foreach($passed_posts as $post)
    @setuppostdata($post)
    <h1>@title</h1>
    @content
@endforeach
@resetpostdata

Thanks!

EDIT: never mind, i just found out that my first example makes no sense as @posts does exactly this.
And second one is equivalent to @posts($passed_query) ... @endposts

Add missing directive for dynamic sidebars

Although not needed in the FSE future. It would be nice to have a simple directive to output the recommended sidebar markup.

@activesidebar('footer')
 @sidebar('footer')
@endsidebar('footer')

Maybe it should be hassidebar for consistency but it would be nice to clean up older templates.

AFC Link Array Exception Illegal string offset 'title'

I have set up a link as an array and output to Blade as follows:

<h5><a title="@sub('casino_header', 'title')" href="@sub('casino_header', 'url')">@sub('casino_header', 'title')</a></h5>

It generally works but when i return to the page I receive the following error

Illuminate \ View \ ViewException (E_ERROR)
Illegal string offset 'title' 

Changing it back to a standard links works ok but when i revert back to an array the same exception is thrown. This is happening randomely on other arrays including images & links. Some work some don't

Site is running version 1.2 on roots/sage 10.0.0

Issue with @published and @modified when trying format the date for a given post

When trying to format a date for a specific post (so outside the loop) with say @published('c', $my_post_id), I got the following error :

ErrorException thrown with message "is_int() expects exactly 1 argument, 2 given (View: /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/resources/views/<partial-or-component-name>.blade.php) (View: /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/resources/views/<partial-or-component-name>.blade.php)"

Stacktrace:
#26 ErrorException in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/storage/framework/views/5c73c21d2feb906cdb575e6a6a17a888e1f9d60c.php:18
#25 Illuminate\View\Engines\CompilerEngine:handleViewException in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/Engines/PhpEngine.php:60
#24 ErrorException in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/storage/framework/views/5c73c21d2feb906cdb575e6a6a17a888e1f9d60c.php:18
#23 Illuminate\View\Engines\CompilerEngine:handleViewException in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/Engines/PhpEngine.php:60
#22 ArgumentCountError in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/storage/framework/views/5c73c21d2feb906cdb575e6a6a17a888e1f9d60c.php:18
#21 is_int in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/storage/framework/views/5c73c21d2feb906cdb575e6a6a17a888e1f9d60c.php:18
#20 require in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/filesystem/Filesystem.php:107
#19 Illuminate\Filesystem\Filesystem:Illuminate\Filesystem\{closure} in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/filesystem/Filesystem.php:108
#18 Illuminate\Filesystem\Filesystem:getRequire in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/Engines/PhpEngine.php:58
#17 Illuminate\View\Engines\PhpEngine:evaluatePath in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/Engines/CompilerEngine.php:61
#16 Illuminate\View\Engines\CompilerEngine:get in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/View.php:139
#15 Illuminate\View\View:getContents in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/View.php:122
#14 Illuminate\View\View:renderContents in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/View.php:91
#13 Illuminate\View\View:render in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/Concerns/ManagesComponents.php:92
#12 Illuminate\View\Factory:renderComponent in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/storage/framework/views/d401be0f5ff0cd450673ff34520d64b8693aac18.php:36
#11 require in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/filesystem/Filesystem.php:107
#10 Illuminate\Filesystem\Filesystem:Illuminate\Filesystem\{closure} in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/filesystem/Filesystem.php:108
#9 Illuminate\Filesystem\Filesystem:getRequire in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/Engines/PhpEngine.php:58
#8 Illuminate\View\Engines\PhpEngine:evaluatePath in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/Engines/CompilerEngine.php:61
#7 Illuminate\View\Engines\CompilerEngine:get in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/View.php:139
#6 Illuminate\View\View:getContents in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/View.php:122
#5 Illuminate\View\View:renderContents in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/vendor/illuminate/view/View.php:91
#4 Illuminate\View\View:render in /<path-to-bedrock-project>/web/app/themes/<sage-theme-name>/index.php:15
#3 include in /<path-to-bedrock-project>/web/wp/wp-includes/template-loader.php:106
#2 require_once in /<path-to-bedrock-project>/web/wp/wp-blog-header.php:19
#1 require in /<path-to-bedrock-project>/web/index.php:6
#0 require in /<path-to-home>/.composer/vendor/laravel/valet/server.php:214

Same with @modified directive, but it seems to work in cases, I don't need to provide an ID (eg: @published('c')).

@published issue

Sorry, now seems to be throwing up another error:

<time class="entry-time"> <span>@published('F j, Y')</span> <span itemprop="datePublished" content="@published('c')"></span> </time>
screenshot 2019-02-12 at 23 04 37

this library breaks the sage 9 sage cli / post install process

on windows we need to run the sage post install process manually

ie vendor\bin\sage.bat preset etc

however this throws the following error

PHP Fatal error:  Uncaught Error: Call to undefined function App\Directives\add_action() in D:\dev\test\roots\bedrock\web\app\themes\sage\vendor\log1x\sage-directives\src\Directives.php:48
Stack trace:
#0 D:\dev\test\roots\bedrock\web\app\themes\sage\vendor\log1x\sage-directives\src\Directives.php(73): App\Directives\Directives->__construct()
#1 D:\dev\test\roots\bedrock\web\app\themes\sage\vendor\composer\autoload_real.php(66): require('D:\\dev\\test\\roo...')
#2 D:\dev\test\roots\bedrock\web\app\themes\sage\vendor\composer\autoload_real.php(56): composerRequire252af4a6338f1ee1f66c597f9df2708d('306c972fefb7062...', 'D:\\dev\\test\\roo...')
#3 D:\dev\test\roots\bedrock\web\app\themes\sage\vendor\autoload.php(7): ComposerAutoloaderInit252af4a6338f1ee1f66c597f9df2708d::getLoader()
#4 D:\dev\test\roots\bedrock\web\app\themes\sage\vendor\roots\sage-installer\bin\sage(5): include_once('D:\\dev\\test\\roo...')
#5 {main}  thrown in D:\dev\test\roots\bedrock\web\app\themes\sage\vendor\log1x\sage-directives\src\Directives.php on line 48

please advise,
thanks
J

Randomly Stopped Working, no Error Messages

As the title says, the library stopped working between now and May 5th 2021.

No changes were made to the code declaring the directives. No changes were made to the wordpress database where the data lies.

I'm getting no errors and can confirm that the plugin is loaded in all envrionments.

get sub fields (related items) of item in repeater field

Hi,

is there any way to get sub fields (related items) of items in a repeater field

  • Custom Post Type Foo has a repeater field bar_repeater.
  • each repeated item has a field called 'title' and a Relationship called bars
  • each relationship has one or more related Bar (Custom Post Type) items

this equivalent blade/php for instance might be

@php $bar_repeater = get_field('bar_repeater'); @endphp  
  @foreach($bar_repeater as $bar_repeater_item)
  	<h2>BAR REPEATER ITEM: {{ $bar_repeater_item['title'] }}</h2>
  	<h3>BARS</h3>
  	@foreach($bar_repeater_item['bars'] as $bar)
  		bar: {{ $bar->post_title }}<br />
  	@endforeach
  <hr />
  @endforeach

this doesn't work.. it shows the correct number of items but the @sub('post_title') is empty for the related object, but then i guess it's not actually a sub field.

@fields('bar_repeater')
   <h2>BAR REPEATER ITEM: @sub('title')</h2>
   <h3>Bars</h3>
   @fields('bars')
       bar: @sub('post_title')<br />
   @endfields
   <hr />
@endfields

thanks
J

@role array

Hi, is there any way to use multiple user roles here with @ROLE in an array like you would with:
@if ( current_user_can('administrator') || current_user_can('editor') )

Shortcodes can't be used within ACF fields

Love the directives -- having an issue when coming to use them in the real world though -- we use a shortcode of [phone] for client websites so we can easily swap phone numbers if they change etc. The @field, @sub and @option directives don't allow this.

In raw php, you'd have to run:

echo do_shortcode(get_field('phone', 'options'));

The above still works even if there are no shortcodes found -- is it worth just adding that to the core?

"Target class [blade.compiler] does not exist" after upgrading to Acorn v3

I'm having an issue using sage-directives after upgrading to Acorn v3. I can use directives within blade files as per usual and everything works correctly when viewing the site but I can no longert use wp cli.

  1. Upgrade Acorn from version ^2.1 to version 3.0
  2. Run wp acorn
  3. The cli doesn't return any output and the following error is added to the debug.log:
Next Illuminate\Contracts\Container\BindingResolutionException: Target class [blade.compiler] does not exist. in /app/vendor/illuminate/container/Container.php:891
Stack trace:
#0 /app/vendor/illuminate/container/Container.php(770): Illuminate\Container\Container->build('blade.compiler')
#1 /app/vendor/roots/acorn/src/Illuminate/Foundation/Application.php(860): Illuminate\Container\Container->resolve('blade.compiler', Array, true)
#2 /app/vendor/illuminate/container/Container.php(706): Illuminate\Foundation\Application->resolve('blade.compiler', Array)
#3 /app/vendor/roots/acorn/src/Illuminate/Foundation/Application.php(845): Illuminate\Container\Container->make('blade.compiler', Array)
#4 /app/vendor/roots/acorn/src/Illuminate/Foundation/helpers.php(120): Illuminate\Foundation\Application->make('blade.compiler', Array)
#5 /app/vendor/roots/acorn/src/Roots/helpers.php(108): app('blade.compiler')
#6 /app/web/app/themes/theme/vendor/log1x/sage-directives/src/Directives.php(90): Roots\app('blade.compiler')
#7 /app/web/app/themes/theme/vendor/log1x/sage-directives/src/Directives.php(35): Log1x\SageDirectives\Directives->blade()
#8 /app/web/wp/wp-includes/class-wp-hook.php(307): Log1x\SageDirectives\Directives->Log1x\SageDirectives\{closure}('')
#9 /app/web/wp/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters(NULL, Array)
#10 /app/web/wp/wp-includes/plugin.php(476): WP_Hook->do_action(Array)
#11 /app/web/wp/wp-settings.php(576): do_action('after_setup_the...')
#12 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(1336): require('/app/web/wp/wp-...')
#13 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(1254): WP_CLI\Runner->load_wordpress()
#14 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/LaunchRunner.php(28): WP_CLI\Runner->start()
#15 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/bootstrap.php(78): WP_CLI\Bootstrap\LaunchRunner->process(Object(WP_CLI\Bootstrap\BootstrapState))
#16 phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/wp-cli.php(32): WP_CLI\bootstrap()
#17 phar:///usr/local/bin/wp/php/boot-phar.php(11): include('phar:///usr/loc...')
#18 /usr/local/bin/wp(4): include('phar:///usr/loc...')
#19 {main}
  thrown in /app/vendor/illuminate/container/Container.php on line 891

@hasfield compiled incorrectly

Got a weird issue in Sage 10 with @hasfield not compiling correctly:

This:

@hasfield('menu_section', $menu_id )
    <ul>
        @fields('menu_section', $menu_id)
            <li>
                @sub('section_title')
            </li>
        @endfields
    </ul>
@endfield

Renders to this:

<?php if (get_field('menu_section')[$menu_id]) : ?>
    <ul>
        <?php if (have_rows('menu_section', $menu_id)) : ?><?php while (have_rows('menu_section', $menu_id)) : the_row(); ?>
            <li>
                <?= get_sub_field('section_title'); ?>
            </li>
        <?php endwhile; endif; ?>
    </ul>
<?php endif; ?>

For some reason @hasfield renders as get_field('menu_section')[$menu_id] instead of get_field('menu_section', $menu_id) and doesn't work. If I remove the @hasfield and @endfield the code works find and displays the list of section titles.

I've reverted to ACF code for now as a workaround:

<?php if (get_field('menu_section', $menu_id ) ) : ?>
    <ul>
        @fields('menu_section', $menu_id)
            <li>
                @sub('section_title')
            </li>
        @endfields
    </ul>
<?php endif; ?>

Wordpress @image directive returns image ID instead of get_field function when using ACF

When I using @image directive with ACF key, Blade renders it as wp_get_attachment_image(<image id here>, ...) instead of wp_get_attachment_image(get_field('acf key here'), ...). It is problem because image ID by ACF is dynamic and after change it in dashboard, changes does not make effect until rendered views will not be deleted. It is persistent on application in production mode and very dynamic content.

@thumbnail fails when passing a WP_Post instance as the only parameter

The documentation for @thumbnail says:

To echo the featured image of a specific post, you can pass the post ID or a WP_Post instance as the first parameter:

@thumbnail(1)
@thumbnail(get_post(1))

But if you only pass a single parameter, the directive does:

  1. If the parameter was false, echo the featured image URL.
  2. If the parameter was numeric, echo the featured image for the post with that ID.
  3. Otherwise, treat the parameter as an image size and echo the featured image in that size for the current post.

if (! empty($expression->get(0))) {
if ($expression->get(0) === 'false') {
return "<?= get_the_post_thumbnail_url(get_the_ID(), 'thumbnail'); ?>";
}
if (is_numeric($expression->get(0))) {
return "<?= get_the_post_thumbnail({$expression->get(0)}, 'thumbnail'); ?>";
}
return "<?= get_the_post_thumbnail(get_the_ID(), {$expression->get(0)}); ?>";
}

Proposed solution: Compare the parameter against the list of images sizes provided by wp_get_registered_image_subsizes(). If it matches, current behavior. If not, pass the parameter as the first argument in get_the_post_thumbnail().

Incorrect end directives

In the docs, some of the end directives are incorrect and causes PHP errors like

Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: syntax error, unexpected 'endif' (T_ENDIF)
@hasfield('list')
  <ul>
    @fields('list')
      <li>@sub('item')</li>
    @fields
  </ul>
@endfield

Should be

@hasfield('list')
  <ul>
    @fields('list')
      <li>@sub('item')</li>
    @endfields
  </ul>
@endfield

Took me an embarrassing amount of time to realise why the directives weren't working.

@image directive with empty strings

I think I traced it down to unwrap() in Utilities.php, but I couldn't quite find where things were happening. I probably could if there was a way to die dump things...hmm I wonder if that dump server thing works on Sage 10 now...

Anyways, heres the problem:

@image($image['id'], 'full', ['alt' => '', 'class' => 'bunch of class names',  'loading' => 'lazy'])

sends this error:

"syntax error, unexpected 'class' (T_CLASS), expecting ']'

And if I rearrange it to be not the last entry...

@image($image->id, 'full', ['class' => 'bunch of class names', 'alt' => '',  'loading' => 'lazy'])

Error:

"syntax error, unexpected 'loading' (T_STRING), expecting ']'

And of course the reason I'd want to do this is in case I want to display alt text but aren't sure if there is alt text. Now, you might say, well you can just add a fallback alt text in your controller, but then I'd have to pass it through again, when part of the fun is to have a quick syntax for these things...

Ok thats it. I toyed around with it for awhile and got some weirdness I think is all related to the way its being parsed...not sure what to do!

Parsing the PHP

Having an issue where the PHP isn't parsing for the Directives.

I've installed it via composer, and it exists in the vendor folder okay. I've tried composer update. But issue still persists. Any idea why this might happen, and how to resolve?

Thanks.

Screenshot 2020-06-11 at 01 01 20

Post Class

Can't see directive for 'post_class()'? eg.

<article <?php post_class() ?>>

There seems to be one for body_class() though. Just wondering am I missing it?

Thanks.

Parsing issues with @image directive. Fatal Error

I've run into parsing issues with the @image directive.

Case 1:

When using the directive as follows:

@image($image_id, 'medium', $alt)

The alt attribute is assigned the literal string "$alt" instead of the variable.

The resulting code ends up being...

<?php echo wp_get_attachment_image(
                $image_id,
                'medium',
                false,
                ['alt' => '$alt']
            ); ?>

Case 2:

When using the directive as follows:

@image($image_id, 'medium', ['alt' => $alt, class='alignright'] )

This one results in a Fatal Error

Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: syntax error, unexpected '','' (T_CONSTANT_ENCAPSED_STRING), expecting ']'

The resulting code is...

<?php echo wp_get_attachment_image(
                $image_id,
                'medium',
                false,
                ['alt' => $alt','class' => 'alignright']
            ); ?>

Using @field with number as second parameter always returns the string case

I'm trying to get a field of a specific post, but when I use the directive like this @field('location', $element->ID) it returns the get_field function like this:

<?= get_field('location')[3205]; ?>

This happens because when Util::parse($expression); is used, it makes all the parameters to string and the check on line 68 is !is_string() when actually should be is_numeric().

Access to Acorn container when Sage not active

During a WordPress database upgrade routine, I get this:

Fatal error: Uncaught Error: Call to undefined function app() in /app/vendor/roots/acorn/src/Roots/helpers.php:77

The issue seems to be that during WordPress database upgrade routines, the theme is not available. In wp-settings.php:

// Load the functions for the active theme, for both parent and child theme if applicable.
foreach ( wp_get_active_and_valid_themes() as $theme ) {
	if ( file_exists( $theme . '/functions.php' ) ) {
		include $theme . '/functions.php';
	}
}

// Debug.
var_dump(wp_get_active_and_valid_themes());
❯ lando wp core update-db
array(0) {
}
Fatal error: Uncaught Error: Call to undefined function app() in /app/vendor/roots/acorn/src/Roots/helpers.php:77

You might be wondering why composer's autoloader is loaded — because I'm using a Bedrock-style root composer setup, so "Composer autoloader being run" does not mean "Sage available".

I'm torn as to how this should be solved, but one way to do it is for sage-directives to make sure \Roots\app() is available before calling it. The other way is for sage-directives to check wp_installing() and not run its bootstrapping during WP installation. There are other techniques as well.

@set directive cannot have value with commas.

When using the @set with a value that contains commas, like the following examples...

@set($product_name, apply_filters('woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key))

or...

@set($product_name, "string, with, commas")

will result in....

<?php $_product = apply_filters('woocommerce_cart_item_product'; ?>

...which has unfinished/unclosed parenthesis and all $args missing.

or like this...

<?php $product_name = "string; ?>

...which is missing the last double quote and the rest of the string.

My suggestion would be to add a third parameter in explode() for Util::parse() function like this...

public static function parse($expression)
{
    return collect(explode(',', $expression, 2))
        ->map(function ($item) {
            return trim($item);
        });
}

Adding 2 as the third parameter for explode() will make it so that it only explodes on the first comma.

Can confirm that this works with the two examples provided above.

Alternatively make a new second util method to prevent issues with existing directives that requires explode on all commas.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.