In this Yii2 programming series, I will guide readers to use the newly upgraded Yii2PHP framework. In this tutorial, I'll show you how to add custom JavaScript and CSS scripts and libraries to your Yii application. Yii uses a concept called AssetBundles to manage these resources more easily. For these examples, we'll continue to build on the simple state application from the previous tutorial. As a reminder, I do participate in the comment thread below. If you have no"/> In this Yii2 programming series, I will guide readers to use the newly upgraded Yii2PHP framework. In this tutorial, I'll show you how to add custom JavaScript and CSS scripts and libraries to your Yii application. Yii uses a concept called AssetBundles to manage these resources more easily. For these examples, we'll continue to build on the simple state application from the previous tutorial. As a reminder, I do participate in the comment thread below. If you have no">
search
HomeWeb Front-endHTML TutorialMastering Yii2: Harnessing the Power of Resource Bundles in Programming

掌握 Yii2:在编程中利用资源包的力量

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and provides an overview of the 2014-10 New features of Yii 2.0 released in March. Well>

In this Yii2 programming series, I will guide readers in using the newly upgraded Yii2 PHP framework. In this tutorial, I'll show you how to add custom JavaScript and CSS scripts and libraries to your Yii application. Yii uses a concept called Asset Bundles to make it easier to manage these resources.

For these examples we will continue to build on the simple state application from the previous tutorial.

As a reminder, I do participate in the comment thread below. I'd be particularly interested if you have a different approach, additional ideas, or would like to suggest topics for future tutorials.

What is an asset package?

Yii's resource bundles represent groups of JavaScript and CSS files that need to be included together on a specific page or an entire website. Resource bundles make it easy to group together specific scripts and styles for specific areas of your site. For example, in my Meeting Planner application, I can easily include the Google Places API on only the pages I need.

This is a simple example. We create a \frontend\assets\LocateAsset.php file:

<?php

namespace frontend\assets;

use yii\web\AssetBundle;

class LocateAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
    ];
    public $js = [
      'js/locate.js',
      'js/geoPosition.js',
      'https://maps.google.com/maps/api/js?sensor=false',
    ];
    public $depends = [
    ];
}

Then we load it into our view file - it's really simple:

<?php

use yii\helpers\Html;
use yii\helpers\BaseHtml;
use yii\widgets\ActiveForm;

use frontend\assets\LocateAsset;
LocateAsset::register($this);

...

When you view the source code of our pages, you will see the generated scripts as well as other Yii2 standard resources for forms, Bootstrap, etc.:

<script src="/mp/js/locate.js"></script>
<script src="/mp/js/geoPosition.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="/mp/assets/d9b337d3/jquery.js"></script>
<script src="/mp/assets/ed797b77/yii.js"></script>
<script src="/mp/assets/ed797b77/yii.validation.js"></script>
<script src="/mp/assets/ed797b77/yii.activeForm.js"></script>
<script src="/mp/assets/8c5c0263/js/bootstrap.js"></script>

In this tutorial, I'll guide you through using a resource bundle to integrate character counting into our status form. We'll use this to enforce a character limit, similar to Twitter's 140 character maximum.

If you are interested in seeing this feature in Yii1.x, I implemented it in Building with the Twitter API: OAuth, Read and Post (Tuts).

Build asset package

Create resource package

In the \assets directory, we create StatusAsset.php:

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class StatusAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [];
    public $js = [
      '/js/jquery.simplyCountable.js',
      '/js/twitter-text.js',
      '/js/twitter_count.js',  
      '/js/status-counter.js',
    ];
    public $depends = [
            'yii\web\YiiAsset',
            'yii\bootstrap\BootstrapAsset',
        ];
}

I used a combination of the jQuery simpleCountable plugin, twitter-text.js (Twitter's text processing script based on JavaScript), and the script responsible for URL shaping: twitter_count.js; in Twitter, URLs are counted as 20 characters. These files are in \web\js.

I also created a document ready function to call them in \web\js\status-counter.js. Including yii\web\YiiAsset in our $depends array will ensure that JQuery is loaded whenever we instantiate this resource.

$(document).ready(function()
{
  $('#status-message').simplyCountable({
    counter: '#counter2',
    maxCount: 140,
    countDirection: 'down'
  });
});

Load resource package

Instantiating a resource package is very simple, as shown in the following \views\status\_form.:

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

use app\assets\StatusAsset;
StatusAsset::register($this);

/* @var $this yii\web\View */
/* @var $model app\models\Status */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="status-form">
    <?php $form = ActiveForm::begin(); ?>
    
    <div class="row">
      <div class="col-md-8">
      <?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>
      </div>
      <div class="col-md-4">
      <p>Remaining: <span id="counter2">0</span></p>
      </div>
    </div>

That’s all you need to activate our Twitter-style character counter:

掌握 Yii2:在编程中利用资源包的力量

I find Yii Asset Bundles simple and easy to manage. They help me reuse parts of JavaScript and CSS in certain areas of the application in an organized way.

What’s next?

The Yii2 Definitive Guide describes many of the advanced features of Asset Bundles. You can control where the scripts are loaded for each package, e.g. POS_HEAD, POS_END. You can set up asset mappings to load specific compatible versions of libraries. You can set JavaScript and CSS options to further conditionally load bundles. You can also use resource converters to compile LESS code to CSS or TypeScript to JavaScript.

Check out the upcoming tutorials in my "Programming with Yii2" series as we continue to dive into different aspects of the framework. You may also want to check out my "Building Your Startup with PHP" series, which uses advanced templates for Yii2 as I build real-world applications.

I welcome feature and theme requests. You can post them in the comments below or send me an email on my Lookahead Consulting website.

If you would like to know when the next Yii2 tutorial is released, follow me on Twitter @reifman or check out my instructor page. My instructor page will immediately contain all articles from this series.

  • The Definitive Guide to Yii2: Assets
  • Yii2 AssetBundle class documentation
  • Yii2 Developer Exchange, the author's Yii2 resource site

The above is the detailed content of Mastering Yii2: Harnessing the Power of Resource Bundles in Programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML vs. CSS and JavaScript: Comparing Web TechnologiesHTML vs. CSS and JavaScript: Comparing Web TechnologiesApr 23, 2025 am 12:05 AM

HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.