Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Support nested urls for nested modules] #twill

By default Twill will disply the url of a module item to be {siteurl}/{module}/{slug} e.g. mysite.com/pages/about. With the 'about' section being the editable slug. This is understandable as Twill knows nothing of your frontend routing. However it is likely confusing for editors, as that url presented will not be the final url of the content.

Remove module name form url

This will give us more correct urls e.g. mysite.com/about

// app/Http/Controllers/Admin/PageController

	protected $permalinkBase = '';

Allow for nested pages to have correct urls

To achieve this we need to set permalinkBase dynamically with a function.

// app/Http/Controllers/Admin/PageController

	protected $permalinkBase = '';

	public function __construct(Application $app, Request $request) {
        parent::__construct($app, $request);

        $this->permalinkBase = $this->getPermalinkBase($request);
    }


	protected function getPermalinkBase($request) {
        $param = strtolower($this->modelName);
        $id = $request->route($param);
        
      	if( !$id ) {
            return  $this->permalinkBase;
        }

        $item = $this->repository->getById($id);
        if( !$item->isRoot() ) {
            $permalinkBase = '';
            $ancestors = $item->ancestors()->with('slugs')->get();
            foreach($ancestors as $ancestor) {
                $permalinkBase .= '/'. $ancestor->slug;
            }
            //remove first slash and return
            return substr( $permalinkBase . $this->permalinkBase, 1);
        } else {
            return  $this->permalinkBase;
        }
    }
@Dmi3yy
Copy link

Dmi3yy commented May 25, 2021

And need add use directives:

use Illuminate\Foundation\Application;
use Illuminate\Http\Request;

@chrispymm
Copy link
Author

Yes, you're probably right! This wasn't really intended to be fully compprehensive instructions - just a note-to-self reminder. Also PHPStorm adds the use statements for me ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment