Giter Site home page Giter Site logo

shipu / themevel Goto Github PK

View Code? Open in Web Editor NEW
344.0 11.0 70.0 114 KB

Theme and asset management for laravel

License: Creative Commons Zero v1.0 Universal

PHP 100.00%
theme child-theme assets laravel themevel management switch-theme theme-switcher theme-generator specific-theme

themevel's Introduction

Laravel-Themevel

Latest Stable Version Latest Stable Version Latest Unstable Version License

Themevel is a Laravel theme and asset management package. You can easily integrate this package with any Laravel based project.

Features

  • Custom theme path
  • Override theme
  • Parent theme support
  • Unlimited Parent view finding
  • Asset Finding
  • Theme translator support
  • Multiple theme config extension
  • Multiple theme changelog extension
  • Artisan console commands
  • Theme enable only Specific route via middleware
  • Almost everything customizable
  • Also Laravel 5.5 to Laravel 10 Supported

Installation

Themevel is a Laravel package so you can install it via Composer. Run this command in your terminal from your project directory:

composer require shipu/themevel

Wait for a while, Composer will automatically install Themevel in your project.

Configuration

Below Laravel 5.5 you have to call this package service in config/app.php config file. To do that, add this line in app.php in providers array:

Shipu\Themevel\Providers\ThemevelServiceProvider::class,

Below Laravel 5.5 version to use facade you have to add this line in app.php to the aliases array:

'Theme' => Shipu\Themevel\Facades\Theme::class,

Now run this command in your terminal to publish this package resources:

php artisan vendor:publish --provider="Shipu\Themevel\Providers\ThemevelServiceProvider"

Artisan Command

Run this command in your terminal from your project directory.

Create a theme directory:

php artisan theme:create your_theme_name


 What is theme title?:
 > 

 What is theme description? []:
 > 

 What is theme author name? []:
 >  

 What is theme version? []:
 > 

 Any parent theme? (yes/no) [no]:
 > y

 What is parent theme name?:
 > 

List of all themes:

php artisan theme:list

+----------+--------------+---------+----------+
| Name     | Author       | Version | Parent   |
+----------+--------------+---------+----------+
| themeone | Shipu Ahamed | 1.1.0   |          |
| themetwo | Shipu Ahamed | 1.0.0   | themeone |
+----------+--------------+---------+----------+

Example folder structure:

- app/
- ..
- ..
- Themes/
    - themeone/
        - assets
            - css
                - app.css
            - img
            - js
        - lang
            - en
                -content.php
        - views/
            - layouts
                - master.blade.php
            - welcome.blade.php
        - changelog.yml        
        - theme.json
     - themetwo/   

You can change theme.json and changelog.yml name from config/theme.php

// ..
'config' => [
    'name' => 'theme.json',
    'changelog' => 'changelog.yml'
],
// ..

json, yml, yaml, php, ini, xml extension supported.

For example:

// ..
'config' => [
    'name' => 'theme.json',
    'changelog' => 'changelog.json'
],
// ..

Then run theme:create command which describe above.

Now Please see the API List Doc.

View Finding Flow:

Suppose you want find welcome.blade.php

 - At first check your active theme 
 - If `welcome.blade.php not found in active theme then search parent recursively
 - If `welcome.blade.php not found in parents theme then search laravel default view folder resources/views

API List

set

For switching current theme you can use set method.

Theme::set('theme-name');

get

For getting current theme details you can use get method:

Theme::get(); // return Array

You can also get particular theme details:

Theme::get('theme-name'); // return Array
Theme::get('theme-name', true); // return Collection

current

Retrieve current theme's name:

Theme::current(); // return string

all

Retrieve all theme information:

Theme::all(); // return Array

has

For getting whether the theme exists or not:

Theme::has(); // return bool

getThemeInfo

For info about the specified theme:

$themeInfo = Theme::getThemeInfo('theme-name'); // return Collection

$themeName = $themeInfo->get('name');
// or
$themeName = $themeInfo['name'];

Also fallback support:

$themeInfo = Theme::getThemeInfo('theme-name'); // return Collection

$themeName = $themeInfo->get('changelog.versions');
// or
$themeName = $themeInfo['changelog.versions'];
// or you can also call like as multi dimension
$themeName = $themeInfo['changelog']['versions'];

assets

For binding theme assets you can use the assets method:

Theme::assets('your_asset_path'); // return string

It's generated at BASE_URL/theme_roots/your_active_theme_name/assets/your_asset_path

If your_asset_path does not exist then it's find to active theme immediate parent assets folder. Look like BASE_URL/theme_roots/your_active_theme_parent_name/assets/your_asset_path

When using helper you can also get assets path:

themes('your_asset_path'); // return string

If you want to bind specific theme assets:

Theme::assets('your_theme_name:your_asset_path'); // return string
// or 
themes('your_theme_name:your_asset_path'); // return string

Suppose you want to bind app.css in your blade. Then below code can be applicable:

<link rel="stylesheet" href="{{ themes('app.css') }}">

Specific theme assets:

<link rel="stylesheet" href="{{ themes('your_theme_name:app.css') }}">

lang

The lang method translates the given language line using your current theme localization files:

echo Theme::lang('content.title'); // return string
// or
echo lang('content.title'); // return string

also support

echo Theme::lang('content.title', [your replace array], 'your desire locale'); // return string
// or
echo lang('content.title', [your replace array], 'your desire locale'); // return string

If you want to bind specific theme assets:

echo Theme::lang('your_theme_name::your_asset_path'); // return string
// or 
echo lang('your_theme_name::your_asset_path'); // return string

How to use in Route

Route::get('/', function () {
    Theme::set('your_theme_name');
    return view('welcome');
});

This will firstly check if there is a welcome.blade.php in current theme directory. If none is found then it checks parent theme, and finally falls back to default Laravel views location.

If you want to specific theme view:

Route::get('/', function () {
    Theme::set('your_theme_name');
    return view('your_theme_name::welcome');
});

Set theme using route middleware

A helper middleware is included out of the box if you want to define a theme per route. To use it:

First register it in app\Http\Kernel.php:

protected $routeMiddleware = [
    // ...
    'theme' => \Shipu\Themevel\Middleware\RouteMiddleware::class,
];

Now you can apply the middleware to a route or route-group. Eg:

Route::group(['prefix' => 'admin', 'middleware'=>'theme:Your_theme_name'], function() {
    // ... Add your routes here 
    // The Your_theme_name will be applied.
});

Set theme using web middleware

A helper middleware is included out of the box if you want to define a theme per route. To use it:

First register it in app\Http\Kernel.php:

protected $middlewareGroups = [
    'web' => [
        // ...
        \Shipu\Themevel\Middleware\WebMiddleware::class,
    ],
    // ...
];

Theme set from config/theme.php .

Then in your controller you can call your view as you would normally do:

return view('home');  // This will load the home.blade.php from the the folder you set in your `config/theme.php`

Dependency Injection

You can also inject theme instance using ThemeContract, eg:

use Shipu\Themevel\Contracts\ThemeContract;

private $theme;

public function __construct(ThemeContract $theme)
{
    $this->theme = $theme
}

Troubleshooting

Clear config after runing vendor publish (see Config section) to save issues related to config caching by running:

php artisan config:cache

php artisan config:clear

Credits

Support for this project

Hey dude! Help me out for a couple of 🍻!

Beerpay Beerpay

themevel's People

Contributors

bricklou avatar carlwhittick avatar cweet avatar jpagny avatar junaidqadirb avatar kohenkatz avatar lex111 avatar mikebarlow avatar rgasch avatar ridislam avatar shipu avatar tmtung144 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

themevel's Issues

Set theme from controllers

I can't set theme from my controller like this:

public function switchTheme(Request $request)
{
    $request->validate([
        'theme' => ['required', 'string']
    ]);

     Theme::set($request->theme);

     return redirect()->route('admin.settings.index', ['p' => 'theme'])
        ->with('toast', 'success')
        ->with('message', 'Thème ' . Theme::current() . ' appliqué avec succès');
}

Theme::current() value still the Default active Theme in config/theme.php

Livewire polling issue

Hello,

The package works fine without polling but when I use the wire:poll feature, I get InvalidArgumentException.

InvalidArgumentException View [livewire.admin.deploy-soft] not found.

Not able to download, conflicts with symfony/yaml

I am sharing here my Composer.Json which has symfony/yaml installed as per your requirement shows, but still after it show that
Using version ^2.2 for shipu/themevel
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- shipu/themevel v2.2.2 requires symfony/yaml 5.1.x-dev -> satisfiable by symfony/yaml[5.1.x-dev] but these conflict with your requirements or minimum-stability.
- shipu/themevel v2.2.1 requires symfony/yaml 5.1.x-dev -> satisfiable by symfony/yaml[5.1.x-dev] but these conflict with your requirements or minimum-stability.
- shipu/themevel v2.2 requires symfony/yaml 5.1.x-dev -> satisfiable by symfony/yaml[5.1.x-dev] but these conflict with your requirements or minimum-stability.
- Installation request for shipu/themevel ^2.2 -> satisfiable by shipu/themevel[v2.2, v2.2.1, v2.2.2].

Installation failed, reverting ./composer.json to its original content.


{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.3",
        "laravel/framework": "^7.30.4",
        "intervention/image": "^2.3",
        "razorpay/razorpay": "^2.2",
        "simplesoftwareio/simple-sms": "^3.1",
        "simplesoftwareio/simple-qrcode": "^2.0",
        "mongodb/mongodb": "^1.4",
        "alcaeus/mongo-php-adapter": "^1.1",
        "league/flysystem-aws-s3-v3": "~1.0",
        "league/flysystem-cached-adapter": "^1.0",
        "kreait/firebase-php": "^4.35",
        "baklysystems/laravel-chat-messenger": "^1.7",
        "pusher/pusher-php-server": "^4.1",
        "ktamas77/firebase-php": "^2.2",
        "phpoffice/phppresentation": "^0.9.0",
        "geoip2/geoip2": "~2.0",
        "vimeo/laravel": "^5.6",
        "symfony/yaml": "5.1.x-dev"

    },

    "require-dev": {
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~6.0",
        "symfony/css-selector": "3.1.*",
        "symfony/dom-crawler": "3.1.*"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "files": [
            "app/constants.php",
            "app/helpers.php",
            "app/language_helper.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "provide": {
        "ext-mongo": "*"
    },
    "config": {
        "preferred-install": "dist"
    }
}

Cannot change "Themes" folder

I installed V2.1 but whenever i change "Themes" folder to either "themes" or "files" or anything else i get error 404

What about template error pages?

We can override laravel error pages with putting error files(404.blade.php, 500.blade.php etc.) into "resources/views/errors" folder.

I put error pages in my template folder(etc themes/dashboard/views/errors/404.blade.php) but it didn't work.

How can override error pages in template views?

I know its about exception handling, we must add template path in view config paths.

But we need proper implementation.

image

Laravel 10 support

Is this package supports Laravel 10?

Iam getting error and not installing on Laravel 10

Please do needful

Using in Service Prodiver

When using Theme::current() in service provider it returns an empty string. I try to use themevel together with nwidart modules package and for the modules to find the views it is necessary to add the current theme path into the Modules service provider like this:

public function registerViews()
    {
        $themePath = base_path('Themes/'.Theme::current().'/views/modules/'. $this->moduleNameLower);

        $viewPath = resource_path('views/modules/' . $this->moduleNameLower);

        $sourcePath = module_path($this->moduleName, 'Resources/views');

        echo($themePath);

        $this->publishes([
            $sourcePath => $viewPath
        ], ['views', $this->moduleNameLower . '-module-views']);

        $this->loadViewsFrom(array_merge([$themePath], $this->getPublishableViewPaths(), [$sourcePath]), $this->moduleNameLower);
    }

but $themePath return:
/var/www/html/Themes//views/modules/installer

Bug in ThemeGeneratorCommand : title_case

Hi.

There is a little bug, when i launched this command (at description) :

  Call to undefined function Shipu\Themevel\Console\title_case()
  at vendor/shipu/themevel/src/Console/ThemeGeneratorCommand.php:146

I have checked the code source, indeed, since laravel 5.7, the method title_case is remplaced by Str::title
See manual : https://laravel.com/docs/7.x/helpers#method-title-case

I will try to do a pull request to fix it. ( It is my first time). Maybe it is better to create another branches : 1 for < 5.7 and 1 another for >= 5.7.

( I love your package :-) )

Best regards.

Parent Theme blade not loading in child theme

I have following configuration in theme.json

{
"name": "childtheme",
"title": "childtheme",
"description": "",
"author": "code",
"version": "1.0",
"parent": "parenttheme"
}

also have blade template called home.blade.php in parent theme but when i activate child theme ,its not picking parent theme home.blade.php

in controller i have

$activeTheme=Theme::current();

    return view($activeTheme.'::home',['activeTheme'=>$activeTheme]);

In app service provider i have

public function boot()
{
Theme::set('childtheme');
}

Using "laravel/framework": "^8.12", "shipu/themevel": "^2.2" ,Linux machine

how i can solve this issue ?

Thanks

Can't Use @yield

My Theme's Name:

@extends('chape::layouts.main')
@section('content')

Error Code: View [layouts.main] not found. (View: /home/vagrant/projects/alternate-cms/Themes/chape/views/index.blade.php)

How can i solve it? Thanks...

laravel 9 set background image

Hi i have following code

style="background-image:url({{themes('/media/misc/bg.png')}})"

but it produce error in console like below

GET http://127.0.0.1:8000/Themes/metrossets%0media/misc/bg.png 404 (Not Found)

also if i add slash at the beginning like background-image:url({{themes('/media/misc/bg.png')}}) then

GET http://127.0.0.1:8000/Themes/metrossets/media/misc/bg.png 404 (Not Found)

how to solve this ?

Thanks

Wrong theme url

Hi,
Using:
<link rel="stylesheet" href="{{ themes('css/app.css') }}">

in a view it creates this url: http://www.somedomain.com/<theme_name>/assets/css/app.css
but it should be http://www.somedomain.com/themes/<theme_name>/assets/css/app.css that corresponds to the symlink created in the public folder. Is this a bug or am I doing something wrong?

Thanks

Creating theme throws error after entering destription.

After entering the Description when running the php artisan theme:create dark command, it throws an error.

/o/l/h/l/rhythm-hub (main) [1]> php artisan theme:create dark

 What is theme title?:
 > dark

 What is theme description? []:
 > dark theme


   Error 

  Call to undefined function Shipu\Themevel\Console\title_case()

  at vendor/shipu/themevel/src/Console/ThemeGeneratorCommand.php:128
    124▕     {
    125▕         $this->theme['title'] = $this->ask('What is theme title?');
    126▕ 
    127▕         $this->theme['description'] = $this->ask('What is theme description?', false);
  ➜ 128▕         $this->theme['description'] = !$this->theme['description'] ? '' : title_case($this->theme['description']);
    129▕ 
    130▕         $this->theme['author'] = $this->ask('What is theme author name?', false);
    131▕         $this->theme['author'] = !$this->theme['author'] ? 'Shipu Ahamed' : title_case($this->theme['author']);
    132▕ 

      +13 vendor frames 

  14  artisan:35
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

Use case where `$themeInfo` in manager file can be null

I found a bug while trying to use the fallback as a default theme.

Since there is no theme specified, the app crash because $themeInfo line 204 of src/Managers/Theme.php is null.
image

To prevent this, a check should be done:

if (!file_exists($fullPath) && $themeInfo->has('parent') && !empty($themeInfo->get('parent'))) {
    $themePath = str_replace(base_path().DIRECTORY_SEPARATOR, '', $this->getThemeInfo($themeInfo->get('parent'))->get('path')).DIRECTORY_SEPARATOR;
    $fullPath = $themePath.$assetPath.$path;

    return $fullPath;
}

"Cannot create a file when that file already exists." message when using php artisan

I found this rather harmless effect after creating themes. Whenever I'm using any php artisan command like php artisan --version I keep getting a message "Cannot create a file when that file already exists." and then the execution happens normally.

I'm using Laravel 8.83.20.

I suspect it keeps trying to generate symbolic link in the public folder, as simply putting a Themes folder and running the php artisan --version command generated the symbolic link. Hope you look into this and sort it out.

how active theme works?

i have set the 'active' =>'arch' in config/theme.php
but, my views dont take the theme arch.
I'm normally using view('someview') on the controller.
I have to do something for these themes to go to all the views?
If i use middleware works, but i don't want to do it in middleware.

How can I add global variable for base layout ?

How can I add global variable for base layout ?
Usually I use View :: composer. Currently with the theme I do not know how?

View::composer(['skins.*'], function ($view) {

            $pagewebsites = PageWebsite::active()->get();

            $view->with('pagewebsites', $pagewebsites);

});

Like that code.
Thank you

title_case function missing.

Error

Call to undefined function Shipu\Themevel\Console\title_case()
at vendor/shipu/themevel/src/Console/ThemeGeneratorCommand.php:146
142| {

Localization Parameter

Hi, the parameters options are not available when using the translation feature. Can you help with this?

I am interested in using the themevel...

I am interested in creating a interface like wordpress for choosing the theme can i use this package ... I am little confused so writing this message..

please guide me

Is the project dead?

I see some issues and nobody answering, is the project dead?
in that case, please announce it, so we move to a different solution.

Security issue

Since there is a symbolic link (symlink) to the /public folder, your entire views code is exposed to the public.

This means that the contents of the views directory, which typically should be private and only accessible server-side, can be accessed by anyone. This represents a significant security risk, as it could potentially expose sensitive code and data.

Cheers

Livewire support

Can you include Livewire? Many developers use it and it would be great to have Livewire as well.

How to change default directory?

I want to change the default directory

My Theme Config "theme.php":
'theme_path' => base_path('resources/themes'),

resources/themes/default/views/welcome.blade.php:
<link rel="stylesheet" href="{{ themes('css/app.css') }}">

browser response:
http://theme.dev/urces/themes/default/assets/css/app.css

Where does "urces" come from?

Would you test the folder change?

There is a problem here.

Thank you

Problem when trying to create a new Theme

I'm trying to execute the command php artisan theme:create your_theme_name but I received an error mkdir() permission denied so I have tried to run the command with sudo and this happens:

image

Theme trying to load when null or blanks

If the active theme is configured as null or blank there doesn't seem to be any reason a theme should attempt to be loaded.

Theme [ ] not found! Maybe you're missing a theme.json file.

Make this less opinionated

Although I really like what you have done here I think it could be a little less opinionated.

For example it's extensive use of ucfirst() could be better. It shouldn't decide for us how to case our description or author. Defaulting the author to your own name isn't something I would personally do either.

The same can be said about the symlink. This defaults to 'Themes'. This is personal preference but I would probably use a different name for this. It would be great if we could configure the name of the symlink instead.

Happy to help with PR's of course.

Issue in asset path from parent theme

There is an issue when getting assets path from parent theme on windows machine. Given below patch may help resolve the issue.

$themePath = str_replace(base_path().DIRECTORY_SEPARATOR, '', $this->getThemeInfo($themeInfo->get('parent'))->get('path') ).'/';
parent-them-assets-path.txt

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.