Add suneditor css file with symfony webpack-encore - symfony

I'm trying to ad suneditor to a symfony project using webpak-encore , I have created a js file
htmlEditor.js
with this code
import SUNEDITOR from 'suneditor'
import 'suneditor/dist/css/suneditor.min.css'
import plugins from 'suneditor/src/plugins'
const editor = SUNEDITOR.create((document.getElementById('appbundle_popup_description') || 'appbundle_popup_description'),{
// All of the plugins are loaded in the "window.SUNEDITOR" object in dist/suneditor.min.js file
// Insert options
// Language global object (default: en)
//lang: SUNEDITOR_LANG['en'],
height: 400,
plugins: plugins,
buttonList: [
['undo', 'redo'],
['font', 'fontSize', 'formatBlock'],
['paragraphStyle', 'blockquote'],
['bold', 'underline', 'italic', 'strike', 'subscript', 'superscript'],
['fontColor', 'hiliteColor', 'textStyle'],
['removeFormat'],
'/', // Line break
['outdent', 'indent'],
['align', 'horizontalRule', 'list', 'lineHeight'],
['table', 'link', 'image', 'video', 'audio' /** ,'math' */], // You must add the 'katex' library at options to use the 'math' plugin.
/** ['imageGallery'] */ // You must add the "imageGalleryUrl".
['fullScreen', 'showBlocks', 'codeView'],
['preview', 'print'],
['save', 'template']
]
});
then I've included an entry in webpack.config.js
.addEntry('htmlEditor', './assets/js/htmlEditor.js')
and I've included the files at the view file
{% block stylesheets %}
{{ parent() }}
{{ encore_entry_link_tags('htmlEditor') }}
{% endblock %}
{% block javascripts %}
{{ parent() }}
{{ encore_entry_script_tags('htmlEditor') }}
{% endblock %}
and then the js file ins included but not the css file, how can I include the css file ?

I have the same problem.
I have a solution for waiting a better solution.
Invcude the CDN in your html after the block javascript in your html head
<link href="https://cdn.jsdelivr.net/npm/suneditor#latest/dist/css/suneditor.min.css" rel="stylesheet">
Better solution
copy the files
suneditor/src/assets/css/suneditor-contents.css for the editing part
and
suneditor/src/assets/css/suneditor.css for your view
After import in your app.js
import '../assets/suneditor-contents.css'
and for your back
import '../assets/suneditor.css'

Related

How do I get a webpack bundled files to run?

I have several JavaScript files created via Webpack. Besides the general app.js I also have JavaScript files that are only used on certain pages. After the build process, I have included the new JavaScript file included. The JS file is also loaded successfully. But the JavaScript does not run.
What do I have to do to make it work? Or am I already doing something wrong?
Goal run my build/myjs.js file and print console.log('Hello world!');
webpack.config.js
Encore
// …
.addEntry('app', './assets/app.js')
.addEntry('myjs', './assets/scripts/my.js')
// …
build/myjs.js
(self["webpackChunk"] = self["webpackChunk"] || []).push([["myjs"],{
/***/ "./assets/scripts/myjs.js":
/*!********************************!*\
!*** ./assets/scripts/myjs.js ***!
\********************************/
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__)
=> {
__webpack_require__(/*! core-js/modules/es.array.for-each.js */
"./node_modules/core-js/modules/es.array.for-each.js");
__webpack_require__(/*! core-js/modules/es.object.to-string.js */
"./node_modules/core-js/modules/es.object.to-string.js");
__webpack_require__(/*! core-js/modules/web.dom-collections.for-each.js */
"./node_modules/core-js/modules/web.dom-collections.for-each.js");
__webpack_require__(/*! core-js/modules/es.array.concat.js */
"./node_modules/core-js/modules/es.array.concat.js");
__webpack_require__(/*! core-js/modules/es.promise.js */
"./node_modules/core-js/modules/es.promise.js");
console.log('Hello world!');
// ...
My show.html.twig file where I need the special JavaScript:
{% extends 'test/base.html.twig' %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('build/myjs.js') }}"></script>
{% endblock %}
You have add in your twig file the encore_entry_script_tags() helpers function. As parameter you pass the name of the file which you want to include. In your case myjs.
The same you have to do with CSS files. But then use the encore_entry_link_tags() helper function. With the name from the file as parameter. Dont forget to use addStyleEntry('targetName',source).
You just need to use encore_entry_script_tags function, as shown here.
In your case, it would be something like:
{% extends 'test/base.html.twig' %}
{{ encore_entry_script_tags('myjs') }}
The file will be loaded automatically, and as any JS file will be executed when loaded.

Symfony 5.4 Webpack Encore server dev

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

django cms 'TemplateResponse' object has no attribute '_headers'

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.

Which file should I override to change edit form template in Sonata Admin?

I follow this tutorial to add a preview of my image file in my sonata admin (symfony3)
http://symfony.com/doc/current/bundles/SonataAdminBundle/cookbook/recipe_image_previews.html
But I not being able to add the CSS parte. The image is too large.
Should I override one of the sonata templates for it? If yes, which file I change and how do I do it? [I'm pretty new in sonata/symfony3]
If not, how should I add the css file in the project?
My actual code is exactly as the tutorial:
class ImageAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
// get the current Image instance
$image = $this->getSubject();
// use $fileFieldOptions so we can add other options to the field
$fileFieldOptions = array('required' => false);
if ($image && ($webPath = $image->getWebPath())) {
// get the container so the full path to the image can be set
$container = $this->getConfigurationPool()->getContainer();
$fullPath = $container->get('request')->getBasePath().'/'.$webPath;
// add a 'help' option containing the preview's img tag
$fileFieldOptions['help'] = '<img src="'.$fullPath.'" class="admin-preview" />';
}
$formMapper
// ... other fields ...
->add('file', 'file', $fileFieldOptions)
;
}
// ...
}
You'll need to add some code to include a CSS file in your Symfony project. Something similar to
{% stylesheets 'bundles/app/css/*' filter='cssrewrite' %}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
Then you'd put the following CSS from the tutorial into that file.
img.admin-preview {
max-height: 200px;
max-width: 200px;
}
You can learn more about including CSS files with Symfony here.
First you need to make a template that extends SonataAdminBundle:CRUD:base_edit.html.twig, here is an example:
{# BlastBaseEntitiesBundle:CRUD:edit.html.twig #}
{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}
{# ... #}
Then create your css file in Resources/Public/css.
Execute the command bin/console assets:install to publish your stylesheet to the web/bundles directory.
{# blastcore/css corresponds to BlastCoreBundle/Resources/Public/css and web/bundles/blastcore/js #}
<link rel="stylesheet" href="{{ asset(blastcore/css/style.css) }}" />
http://symfony.com/doc/current/assetic/asset_management.html
Now you need to tell sonata to use your template for your admin.
you can do that in the service definition :
admin.yml
blast_base_entities.admin.search_index_entity:
class: Blast\BaseEntitiesBundle\Admin\SearchIndexEntityAdmin
arguments: [~, Blast\BaseEntitiesBundle\Entity\SearchIndexEntity, BlastCoreBundle:CRUD]
tags:
- name: sonata.admin
manager_type: orm
group: admin
label: SearchIndexEntity
calls:
- [ setTemplate, [edit, BlastBaseEntitiesBundle:CRUD:edit.html.twig]]
https://sonata-project.org/bundles/admin/master/doc/reference/templates.html#crudcontroller-actions-templates

How to combine these assetics in Symfony2?

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.

Resources