I've tried to add webpack to a Symfony 3.1 app. The problem is, when I add HMR, the asset function doesn't resolve correctly
// base.html.twig
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
// app/config/config_dev.yml
framework:
assets:
base_path: "http://localhost:8080"
Result: <script src="/http://localhost:8080/bundles/fosjsrouting/js/router.js"></script>
How can I tell Symfony to not prepend the starting / if the base_path begins with http://?
You can use base_urls. Protocol/host/port should not be used in base_path for assets.
https://symfony.com/doc/current/reference/configuration/framework.html#assets
Related
I have a problem with Symfony 5.4 and WebPack yet.
when I want to run the npm run dev-server this one tells me:
<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:3000/, http://127.0.0.1:3000/
<i> [webpack-dev-server] Content not from webpack is served from 'F:\Symfo\api-2021\public' directory
<i> [webpack-dev-server] 404s will fallback to '/index.html'
DONE Compiled successfully in 2064ms
and on the page (localhost or 127.0.0.1) I have Cannot GET / and nothing in the console except that I am missing the favicon
my version of npm is: 8.1.2
my webpack.config.js
const Encore = require('#symfony/webpack-encore');
// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or sub-directory deploy
//.setManifestKeyPrefix('build/')
/*
* ENTRY CONFIG
*
* Each entry will result in one JavaScript file (e.g. app.js)
* and one CSS file (e.g. app.css) if your JavaScript imports CSS.
*/
.addEntry('app', './assets/app.js')
// enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
.enableStimulusBridge('./assets/controllers.json')
// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()
// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()
/*
* FEATURE CONFIG
*
* Enable & configure other features below. For a full
* list of features, see:
* https://symfony.com/doc/current/frontend.html#adding-more-features
*/
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
.configureBabel((config) => {
config.plugins.push('#babel/plugin-proposal-class-properties');
})
// enables #babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = 3;
})
// enables Sass/SCSS support
//.enableSassLoader()
// uncomment if you use TypeScript
//.enableTypeScriptLoader()
// uncomment if you use React
.enableReactPreset()
// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())
// uncomment if you're having problems with a jQuery plugin
//.autoProvidejQuery()
;
module.exports = Encore.getWebpackConfig();
EDIT
this is my Controller
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class AppController extends AbstractController
{
/**
* #Route("/", name="app")
*/
public function index(): Response
{
return $this->render('app/index.html.twig', [
]);
}
}
The template app/index.html.twig
{% extends 'base.html.twig' %}
{% block title %}Hello AppController!{% endblock %}
{% block body %}
<h1>Hello World!</h1>
{% endblock %}
and the base.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
{# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
{% block stylesheets %}
{{ encore_entry_link_tags('app') }}
{% endblock %}
{% block javascripts %}
{{ encore_entry_script_tags('app') }}
{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
and the app.js
import './styles/app.css';
// start the Stimulus application
import './bootstrap';
console.log('test')
Thank you for your help
I am following the django-cms documentation and so far I only have one template home.html:
{% load cms_tags sekizai_tags %}
<html>
<head>
<title>{% page_attribute "page_title" %}</title>
{% render_block "css" %}
</head>
<body>
{% cms_toolbar %}
{% placeholder "content" %}
{% render_block "js" %}
</body>
</html>
And my url.py looks like this:
from django.contrib import admin
from django.urls import path, re_path, include
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^', include('cms.urls')),
]
I can login and create a page, but when I logout and navigate to `localhost:8000' I get:
AttributeError at /
'TemplateResponse' object has no attribute '_headers'
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 3.2
Exception Type: AttributeError
Exception Value:
'TemplateResponse' object has no attribute '_headers'
Exception Location: /usr/local/lib/python3.9/site-packages/cms/cache/page.py, line 84, in set_page_cache
Python Executable: /usr/local/bin/python
Python Version: 3.9.4
Python Path:
['/app/app',
'/usr/local/lib/python39.zip',
'/usr/local/lib/python3.9',
'/usr/local/lib/python3.9/lib-dynload',
'/usr/local/lib/python3.9/site-packages']
I am not sure if I did something wrong here. I would like to see how the webpage looks like for someone who does not have an account and cannot login.
Support for django 3.2 has been introduced in django-cms 3.9 so upgrade to this version to resolve this error.
Here's my config.yml file
framework:
#code
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
packages:
blade:
base_path: '/bundle/bladecms'
#code
I'd like to set base_path for blade prefix to be able to use
<img src="{{ asset('images/image.png', 'blade') }}"/>
instead
<img src="{{ asset('bundle/bladecms/images/image.png') }}"/>
So what's a problem? When I use 'base_path' I get
Unrecognized option "base_path" under "framework.templating.packages.blade"
If I change base_path to base_url I get
"/bundle/bladecms" is not a valid URL
How to configure it properly?
You have to set a valid URL (e.g. http://yourhost/bundle/bladecms) .
Make your configuration like this :
framework:
templating:
packages:
blade:
assets_base_urls: '%router.request_context.scheme%://%router.request_context.host%/bundle/bladecms
And use it like follows :
<img src="{{ asset('images/image.png', 'blade') }}"/>
The first parameter router.request_context.scheme is the protocol used by the request (i.e. http, ssl).
The second router.request_context.host is the host of the request.
Like this, your base_url change dynamically depending on the request.
See http://symfony.com/doc/current/reference/configuration/framework.html#assets-base-urls
I am trying to integrate extjs in my symfony app.
My folder structure:
app
bin
src
tests
var
vendor
web
assets
js
- ext-all.js
- main.js
controller
- controller.js
All js-files are included when my page loads(works fine):
<script src="{{ asset('assets/js/ext-all.js') }}"></script>
<script src="{{ asset('assets/js/main.js') }}"></script>
<script src="{{ asset('assets/js/controller.js') }}"></script>
main.js:
Ext.define('MyApp.Application', {
extend: 'Ext.app.Application',
appFolder: 'web/assets/js',
name: 'MyApp',
controllers: ['controller'],
});
controller.js:
Ext.define('MyApp.controller.Controller', {
extend: 'Ext.app.Controller',
init: function() {
console.log('Initialized');
}
});
When i load page, console throws 404-error:
"NetworkError: 404 Not Found - http://127.0.0.1:8000/web/assets/js/controller/controller.js?_dc=1450088635533"
Why there is this error ?
controller.js is right where it should be or am i wrong?
Anybody could help me with this issue?
thanks and greetings!
I'm using ExposeTranslationBundle (expose translations to javascript) and JMSI18nRoutingBundle (expose routes to javascript). This is part of my <head> tag:
{% javascripts filter='?yui_js' output='js/app.js'
'../app/Resources/public/js/jquery-*.js'
'../app/Resources/public/js/jquery/*'
'../app/Resources/public/js/app.js'
'bundles/fosjsrouting/js/router.js'
'bundles/bazingaexposetranslation/js/translation.js' %}
<script src="{{ asset_url }}" ></script>
{% endjavascripts %}
<!-- ExposeTranslationBundle and JMSI18nRoutingBundle -->
<script src="{{ path('fos_js_routing_js',
{"callback": "fos.Router.setData"}) }}"></script>
<script src="{{ url('bazinga_exposetranslation_js') }}"></script>
Is possible to combine the last two <script> imports into first assetic and how?
I thing it is not possible because the FOSJSRouting javascript file is generated by a controller. Internaly the bundles caches the js but in app/cache, so it needs to go through the controller every request. I'm not familiar with the expose translation bundle but I guess it's the same problem here.
There has been an ongoing discussion in the issue tracke of FOSJsRouterBundle on github and there is also a sollution. See the full issue here: https://github.com/FriendsOfSymfony/FOSJsRoutingBundle/issues/22
The workaround is to have a script or command to dump the output to files in web/js directory:
<?php
require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
use Symfony\Component\HttpFoundation\Request;
$kernel = new AppKernel('stage', false);
$kernel->loadClassCache();
$response = $kernel->handle(Request::create('/js/routing?callback=fos.Router.setData'));
file_put_contents(__DIR__.'/../web/js/routes.js', $response->getContent());
This is somewhat of a workaround sollution. I've been thinking about implementing a generic bundle wich whome this task can be configured for several other bundles using controllers to output js. The controller actions would have to be configured in a yml file and then a command would have have to be executed at each deployment/modification of routes/strings. But I havn't had time for this... yet ;)
Instead of import, you could happily put it inline, ie:
<script type="text/javascript">
{# BazingaExposeTranslation #}
{% render 'bazinga.exposetranslation.controller:exposeTranslationAction'
with { domain_name: "messages", _locale:app.session.locale, _format: "js" } %}
{# JMSI18nRoutingBundle ... #}
</script>
You need to check the routing file for those bundles.