Friday, February 8, 2019

GRAILS : Rendering Groovy GSP Code From A String | Grails – Rendering a Template from a String | Render Grails template from external source




package com.pkm.utils

import grails.util.Holders
import groovy.text.Template
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine
import org.springframework.core.io.ByteArrayResource
import org.springframework.web.context.request.RequestContextHolder

/**
 * Created by pritom on 29/11/2017.
 */
class InvoicePdfUtils extends UtilsBase {
    static def test() {
        GroovyPagesTemplateEngine engine = Holders.applicationContext.getBean(GroovyPagesTemplateEngine)
        StringWriter stringWriter = new StringWriter()

        String content = "CONTENT-\${a}--\${b.none?.none ?: 'None'}-MINE-XXX " +
                "<ui:serverURL/> <g:if test='true'>True</g:if> HERE??? YES ME IS HERE, ".toString()
        Map model = [a: '10', b: [:]]

        String pageName = engine.getCurrentRequestUri(RequestContextHolder.getRequestAttributes().request) // /grails/test.dispatch
        Template template = engine.createTemplate(new ByteArrayResource(content.getBytes("UTF-8"), pageName), pageName, true)
        Writable renderedTemplate = template.make(model)
        renderedTemplate.writeTo(stringWriter)

        println("Request-path=${engine.getCurrentRequestUri(RequestContextHolder.getRequestAttributes().request)}")
        println(stringWriter.toString())
    }
}


This code block will take input from yourself and then parse as a GSP parser and return output as String.

https://little418.com/2009/11/rendering-groovy-gsp-code-from-a-string.html

Try catch not working Laravel raw queries | How to properly catch PHP exceptions (Laravel 5.X) | Why try catch not work in Laravel


Make sure you're using your namespaces properly. If you use a class without providing its namespace, PHP looks for the class in the current namespace. Exception class exists in global namespace, so if you do that try/catch in some namespaced code, e.g. your controller or model, you'll need to do catch(\Exception $e) to catch all your exceptions:  


try {
  //code causing exception to be thrown
}
catch(\Exception $e) {
  //exception handling
}


If you do it like this there is no way to miss any exceptions. Otherwise if you get an exception in a controller code that is stored in App\Http\Controllers, your catch will wait for App\Http\Controllers\Exception object to be thrown.

Laravel 5 Check if request is ajax request | Ajax request validation


<?php
use Illuminate\Support\Facades\Request;

return Request::ajax(); /* True | False */




Getting url() in a Command returns http://localhost | URL generated in a queue - localhost returned | URL in jobs only return localhost | URL problem with queued jobs

First need to specify url to project/config/app.php as below:

<?php
return [
    'url' => 'http://localhost:81/my_laravel_project/'
];

Now need to modify project/app/Providers/RouteServiceProvider.php as below:


<?php
namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function boot(Router $router)
    {
        parent::boot($router);

        $url = $this->app['url'];
        $url->forceRootUrl(config('app.url'));
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function map(Router $router)
    {
        $router->group(['namespace' => $this->namespace], function ($router) {
            require app_path('Http/routes.php');
        });
    }
}

Using custom monolog handlers in Laravel

You can easily add new handlers to Monolog


$manage_monolog = function(\Monolog\Logger $monolog) {
    #New monolog file name
    $filename = storage_path('logs'.DIRECTORY_SEPARATOR.'custom.log');
    $handler = new \Monolog\Handler\RotatingFileHandler($filename);

    #If you only keep this handler only
    $monolog->setHandlers(array($handler));

    #If you need to add this custom handler to existing handlers
    $monolog->pushHandler($handler);

    print_r($monolog->getHandlers());
};
$manage_monolog(\Illuminate\Support\Facades\Log::getMonolog());
\Illuminate\Support\Facades\Log::info("Its completed...");



How to pass data to all views in Laravel 5 | Sharing Data Between Views Using Laravel View Composers | Laravel 5.3 - Sharing $user variable in all views | Passing data to all views | View Composer to pass variable to all views | Passing $variables to multiple views

A view composer is exactly what you're looking for. A view composer allows you to tell your application do x when view y is rendered. For example when pages.buy is rendered anywhere in my application attach $articles.
The main thing is to create a service provider under "project/app/Providers" folder as below:
<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function($view) {
            $view->with('isAdmin', true);
            $view->with('isSupervisor', false);
        });
        /* Make sure you have a view named "index.blade.ctp" in a folder
        named "customFolder" under "project/resources/views" folder.
         */
        view()->composer(array("customFolder.index"), function($view) {
            $view->with("xor", "XOR-1");
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Laravel :: Getting url() in a Command returns http://localhost | URL problem with queued jobs | Url helper functions that are relative to application url config | Localhost url problems

First need to configure project/config/app.php as below:
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/

'url' => 'http://localhost:81/my_project/'
Now need to edit project/app/Providers/AppServiceProvider.php as below:
namespace App\Providers;

use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider
{
    private static $logStream;


    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        URL::forceRootUrl(Config::get('app.url'));
    }
}