How define widget assets file in yii2? - javascript

I try to create a widget in yii2 in this folder:
basic/components/input/
and create "assets" and "view" in that directory.
I created my widget and it works but i need add "CSS" an "JS" file to my widget.
in yii1 can use assets in widget folder but i can't do that in yii2
any body can help me?

I found my Answer.
you should create a AssetBundle in your widget dir like this:
/**
* Define Assets of inout tag widget
*/
namespace app\components\InputTag;
class InputTagAsset extends \yii\web\AssetBundle
{
public $sourcePath = "#app/components/InputTag/assets";
public $css = [
'css/xx.css',
];
}
and then call your AssetBundle in your widget file in init() method like this:
public function init(){
parent::init();
InputTagAsset::register($this->view);
}
and put your files in assets folder.

Related

How to architect ASP.Net app to load Controller specific JS

I have an asp.net app with a site.js which is getting lengthy. What is the proper way to architect the file structure so that /home routes will load a home.js file and /product routes will load a routes.js file?
Ideally I would like to keep all the js files in the wwwroot folder and not next to the views or within them so I can minify them with the compiler
you can create an extension method for Html helper and call that on _Layout.cshtml as #Html.RenderControllerJs(Url); so that it gets called every time and inject the respective js.
public static class HtmlHelperExtentions
{
public static IHtmlContent RenderControllerJs(this HtmlHelper html, UrlHelper urlHelper)
{
var env = html.ViewContext.HttpContext.RequestServices.GetService<IHostEnvironment>();
var controllerName = html.ViewContext.RouteData.Values["Controller"].ToString().ToString();
var jsFileRelativePath = Path.Combine("<folder_path_for_all_controller_js>", $"{controllerName}.js");
var controllerJsFilePath = Path.Combine(env.ContentRootPath, jsFileRelativePath);
if (File.Exists(controllerJsFilePath))
{
return html.Raw(
$"<script type=\"text/javascript\" src=\"{urlHelper.Content(Path.Combine("~", jsFileRelativePath))}\"></script>");
}
return new HtmlString("");
}
}
You can also write custom logic specific to any controller. You have full control now.

model is not working in laravel layout section

I have used this section of code in layout section of my Laravel project:
#php
$setting = setting();
#endphp
As it is a layout I didn't call this file anywhere but included it many times.
And wherever it is included it is showing me this error.
Error
Call to undefined function setting()
What went wrong here?
my setting model is:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $table = 'setting';
protected $primaryKey = 'id';
}
?>
also my full layout file is Here
setting function is defined in the Helper.php file. here it is:
<?php
function setting(){
return \App\Model\Setting::first();
}
?>
how can I fix this? TIA
you don't need to use :
#php
$setting = setting();
#endphp
the composer has a files key (which is an array of file paths) that you can define inside of autoload. so you can add the path of the helpers file in the composer.json file:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/Helpers.php"
]
},
then Run :
composer dump-autoload
after that in your layout you can use {{setting()->email}} or if you use $setting =setting(); in your layout use {{$setting->email}}
Assuming your Manager is properly configured and eloquent booted.
Your file does not get included via composers autoload. But you actually dont need to load it.
#php
$setting = \App\Model\Setting::first();
#endphp

Is it better to register css and js in yii controller?

Yii::app()->getClientScript()->registerCssFile(Yii::app()->theme->baseUrl.'/css/jquery.ad-gallery.css');
Yii::app()->getClientScript()->registerScriptFile(Yii::app()->theme->baseUrl.'/js/jquery.ad-gallery.js', CClientScript::POS_HEAD);
I want to load these files only for one particular view
Or any better idea to import CSS and Javascript in Yii framework for a particular view
Like so:
public function actionIndex()
{
$uri = 'path to your action-specific css';
Yii::app()->clientScript->registerCssFile($uri, 'screen, projection');
}
and like this, if you want controller-specific files:
public function init()
{
$uri = 'path to your controller-specific css';
Yii::app()->clientScript->registerCssFile($uri, 'screen, projection');
return parent::init();
}
If you want this functionality on all controllers, create a subclass of CController, put these methods in there, and change your controllers to use the new subclass.
This will help you definitely

How to organize JavaScript in Yii project

I write project using Yii.I would like to receive advice on how to organize my JavaScript.I thought about several options:
Put all code in one file (app.js), create for each feature moduls and attach it to each page of project.But problem is that not all feature required in all pages and so in this case I have to load useless code and it is difficult to navigate among hundreds of lines.(I know that I can write in separate files and then "compile" all in one, but it does not solve problem of excess code)
Create for each feature separate file and manage it loading through Yii(attach only necessary files to page). But some feature require only couple lines of code and it seems irrational to create file for that.
You could use a mixing of Asset and layout
In a proper layout stored inside your_app\views\layouts\your_asset_filename.php
you could register a specific asset
use your_app\assets\YourAsset;
//use common\models\UserParam;
//use common\models\LandScope;
/* #var $this \yii\web\View */
/* #var $content string */
YourAssest::register($this);
?>
In your_app\asset you could configure the js files you needs
class YourAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'css/site.css',
........
];
public $js = [
'your_js1.js',
'your_js2.js',
....
];
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
and last your controller/action you can set the layout you need for each render
public function actionMyAction()
{
$this->layout = 'your_asset_filename';
...
return $this->render('your_view',[ ....]);
}

Single CSS from appasset.php per page in yii2

I am using the yii2 framework and the following code in appasset.php:
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [ 'css/site.css', 'css/country.css', 'css/admin/one.css', 'css/fg/two.css' ];
public $js = [ ];
public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ];
My page pulls in all of the CSS files listed, but I only want one.css in this page, and to use the other CSS files in other pages.
How can I prevent these other CSS files from appearing in this page? Or - is it possible to create a new appasset.php file for a single php page?
Each specific situation should have its own AssetBundle.
You just create as many as you need and include them in the relevant view file:
Existing one:
class AppAssets extends \yii\web\AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = ['css/site.css', 'css/country.css', 'css/fg/two.css'];
...
}
Additional one:
class AdminAssetBundle extends \yii\web\AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = ['css/admin/one.css'];
public $depends = ['AppAssets'],
}
(Please add namespaces where necessary, I left those out)
As said: Then just include the one you need in the view that is relevant.
ie. in your admin views you add: AdminAsset::register($this);
Because of the depends, those views will automatically include your AppAssets bundle.
If your AppAssets is the one from the yii app distribution (added by default), it is probably already being registered in the /views/layouts/main.php-file.
That means that it is not required to be defined as a dependency.
I do consider it a good practice to keep the dependencies clear (if your admin one.css file actually depends on the ones from AppAssets, if not remove the $depends alltogether).
Yii is smart enough to only include each asset bundle only once anyway.

Categories

Resources