Installation Add the bundle via Composer:
composer require culabs/jquery-bundle
Enable the bundle in config/bundles.php:
return [
// ...
Culabs\JQueryBundle\CulabsJQueryBundle::class => ['all' => true],
];
Basic Usage
Include jQuery in your base template (e.g., base.html.twig):
{{ culabs_jquery_bundle_jquery() }}
This renders the jQuery script tag with the latest version (or configured version) in the <head> or <body>.
First Use Case Use jQuery in a Twig template for simple DOM manipulation:
<script>
$(document).ready(function() {
alert("jQuery is working!");
});
</script>
Version Management
Configure the jQuery version in config/packages/culabs_jquery.yaml:
culabs_jquery:
version: '3.6.0' # Defaults to 'latest'
minified: true # Set to false for development
Override per-template if needed:
{{ culabs_jquery_bundle_jquery({'version': '2.2.4', 'minified': false}) }}
Asset Integration Combine with Symfony’s AssetMapper or Webpack Encore for caching:
{% block javascripts %}
{{ parent() }}
{{ culabs_jquery_bundle_jquery() }}
{{ encore_entry_script_tags('app') }}
{% endblock %}
Twig Extensions Extend the bundle’s Twig functions for custom logic (e.g., conditional loading):
{% if is_granted('ROLE_ADMIN') %}
{{ culabs_jquery_bundle_jquery() }}
{% endif %}
Dependency Loading Load jQuery before other libraries (e.g., DataTables):
{{ culabs_jquery_bundle_jquery() }}
{{ culabs_jquery_bundle_script('//cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js') }}
Version Conflicts
noConflict():
<script>
var $j = jQuery.noConflict();
$j(document).ready(function() { ... });
</script>
Caching Issues
php bin/console cache:clear
Twig Autoloading
bundles.php and the CulabsJQueryBundle is autoloaded.CDN Dependencies
culabs_jquery.yaml:
culabs_jquery:
cdn: false
path: '%kernel.project_dir%/vendor/jquery/dist/jquery.min.js'
<head>/<body> to verify jQuery is loaded.Custom Twig Functions
Extend the bundle’s CulabsJQueryExtension to add helper functions:
// src/Twig/CustomJQueryExtension.php
class CustomJQueryExtension extends \Twig\Extension\AbstractExtension
{
public function getFunctions()
{
return [
new \Twig\TwigFunction('custom_jquery_alert', [$this, 'alertMessage']),
];
}
public function alertMessage($message) {
return '<script>$().ready(function(){ alert("'.$message.'"); });</script>';
}
}
Register in services.yaml:
services:
App\Twig\CustomJQueryExtension:
tags: ['twig.extension']
Event Listeners
Hook into the bundle’s events (e.g., jquery.bundle.init) to modify behavior dynamically.
Environment-Specific Config Use Symfony’s parameter bags to switch between CDN/local based on environment:
# config/packages/dev/culabs_jquery.yaml
culabs_jquery:
cdn: false
path: '%kernel.project_dir%/path/to/local/jquery.js'
How can I help you explore Laravel packages today?