In my symfony project my css is well linked, but my javascript is not working and I can't find why. I guess something stupid I missed ...! I tried with the encore webpack at firt since I'm runninh Sass, but I gave up and switched to the classi src=""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{# Run `composer require symfony/webpack-encore-bundle`
and uncomment the following Encore helpers to start using Symfony UX #}
{% block stylesheets %}
{# {{ encore_entry_link_tags('app') }}#}
{# {{ encore_entry_script_tags('app') }}#}
<link rel="stylesheet" href="{{ asset('bundles/mercuryseriesflashy/css/flashy.css') }}">
<link rel="stylesheet" href="{{ asset('./build/app.css') }}">
{% endblock %}
{% block javascripts %}
{# {{ encore_entry_script_tags('app') }}#}
<!-- Flashy depends on jQuery -->
{% endblock %}
</head>
<body>
{% block navbar %} {% include 'inc/navbar.html.twig'%}{% endblock %}
{% block body %}{% endblock %}
{% block footer %}{% endblock %}
<script src="{{ asset('./build/app.js') }}"></script>
<script src="//code.jquery.com/jquery.js"></script>
</body>
</html>
/*
* Welcome to your app's main JavaScript file!
*
* We recommend including the built version of this JavaScript file
* (and its CSS file) in your base layout (base.html.twig).
*/
// any CSS you import will output into a single css file (app.scss in this case)
import './styles/app.scss';
import './bootstrap';
// start the Stimulus application
const logoMenu = document.querySelector('.logoMenuImg');
const contItems = document.querySelector('.contItems');
const arrItems = document.querySelectorAll('.items');
console.log(logoMenu);
console.log(contItems);
console.log(arrItems);
console.log('arrItems');
alert('hello world');
Thank you for your help
p.s: in the inspector it's blank no erros
If you are using encore_entry_script_tags i assume you have add your JS file in your webpack configuration ?
I see you're using assetic, if you are in Symfony 4.4 and more, remove it, it's deprecated. Use Webpack encore.
let Encore = require('#symfony/webpack-encore');
let CopyWebpackPlugin = require('copy-webpack-plugin');
//let TerserPlugin = require('terser-webpack-plugin');
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')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.addEntry('app', './assets/js/app.js')
.enableSingleRuntimeChunk()
;
module.exports = Encore.getWebpackConfig();
And run with npm run build or yarn encore <env>
Look at documentation: https://symfony.com/doc/current/frontend.html
Related
I know I'm doing something wrong, after consulting the docs and watching 3 YouTube videos that get it spun up in the first 7 min and copying them it still doesn't work
I'm basically trying to get to hello world from clicking a button
The Relevant lines in my HTML
{% extends 'box2.html' %}
{% load static %}
{% block content %}
<button class="btn btn-success mt-3" type="button" onclick="handle_do_thing_click()" type="">Add Planner</button>
{% endblock %}
{% block js_block %}
<script type = "text/javascript/" src="{% static 'js/doThing.js' %}"></script>
{% endblock %}
my settings.py static settings
INSTALLED_APPS = ['django.contrib.staticfiles']
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
my url.py file
from django.urls import path
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [ these work
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
and my js file which exists in app/static/js/doThing.js is hello world
function handle_do_thing_click() {
console.log("hello world");
}
The console error is
Uncaught ReferenceError:
handle_do_thing_click is not defined at HTMLButtonElement.onclick
For me, removing type="text/javascript/" from <script> tag make it work.
I have some Javascript code inside a Twig template that uses jQuery. The script seems to be loading before jQuery, so it throws a $ is not defined error. I can't figure out why it's loading before the main bundle that includes jQuery (compiled with webpack-encore).
JQuery does load because I can reference it from the console or wrap the script inside a setTimeout to force it to be loaded later.
I have this base template:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>
{% block title %}Welcome!
{% endblock %}
</title>
{% block stylesheets %}
{{ encore_entry_link_tags('app') }}
{% endblock %}
{% block javascripts %}
{{ encore_entry_script_tags('app') }}
{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
The page template:
{% extends 'base.html.twig' %}
{% block body %}
/// ...
<script>
$.change(/*...*/); // $ is not defined
</script>
{% endblock %}
webpack.config.js:
const path = require('path');
const Encore = require('#symfony/webpack-encore');
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.enableSassLoader()
.addEntry('app', './assets/app.js')
.enableStimulusBridge('./assets/controllers.json')
.splitEntryChunks()
.enableSingleRuntimeChunk()
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
.configureBabel((config) => {
config.plugins.push('#babel/plugin-proposal-class-properties');
})
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = 3;
})
.autoProvidejQuery()
;
module.exports = Encore.getWebpackConfig();
app.js:
require('./styles/app.scss');
import $ from 'jquery';
global.$ = global.jQuery = $;
This was the generated HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/build/app.css">
<script src="/build/runtime.js" defer></script>
<script src="/build/app.js" defer></script>
</head>
<body>
<main class="col p-4 content flex-grow-1">
<!-- page content -->
<script>
// $ is not defined here
</script>
</main>
</body>
</html>
NOTE: You must note that you can’t use require and import at the same
time in your node program and it is more preferred to use require
instead of import as you are required to use the experimental module
flag feature to run import program.
--https://www.geeksforgeeks.org/difference-between-node-js-require-and-es6-import-and-export/
The article above also mentions that with require "you can directly run the code" in this case the code is defining the $ function, so you want to run that.
My projects are as follows with no problems:
app.js:
require('./styles/app.scss');
const $ = require('jquery');
window.$ = $;
Comment the following line in webpack.config.js:
//.autoProvidejQuery()
The problem was found in these lines from the generated HTML:
<script src="/build/runtime.js" defer></script>
<script src="/build/app.js" defer></script>
The defer attribute forces the Javascript files where jQuery is defined, to be loaded after the page is rendered. Since I'm adding inline Javascript in the page, it's loaded before app.js.
Since there is no way to add deferred inline Javascript in HTML, there are two alternatives:
Set the following configuration in config/packages/webpack_encore.yaml:
script_attributes:
defer: false
This disables the behavior described. This solution is not ideal because using defer is desirable in my case.
Define Javascript code outside of the template (import it with encore_entry_script_tags).
Save your Javascript file in assets/ and, if you have a similar base template as the one in the question, import it in your page template like this:
{% block javascripts %}
{{ parent() }}
{{ encore_entry_script_tags('your_file') }}
{% endblock %}
In webpack.config.js:
Encore
//...
.addEntry('your_file','./assets/your_file.js');
I code with django and when I am working with django template, I do the below to avoid repeating code. Let me illustrate it with an example:
Suppose I have two pages in my website:
1) home
2) about
In django I code as below:
I first build a base.html :
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}home{% endblock title %}</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'css/my-base-css.css' %}">
{% block stylesheet %}{% endblock stylesheet %}
</head>
<body>
<h1>this is my site</h1>
{% block body %}{% endblock body %}
</body>
</html>
I then build home.html:
{% extends 'base.html' %}
{% block stylesheet %}<link rel="stylesheet" href="{% static 'css/home-page-css.css' %}">
{% endblock stylesheet %}
{% block body %}
<h2>This is home</h2>
{% endblock body %}
I also build about.html:
{% extends 'base.html' %}
{% block title %}
my-website-about
{% endblock title %}
{% block stylesheet %}<link rel="stylesheet" href="{% static 'css/about-page-css.css' %}">
{% endblock stylesheet %}
{% block body %}
<h2>This is about</h2>
{% endblock body %}
I now want to do the same without having a backend. I have a static website. How can I do the same without having a backend like django or php, etc.?
There is a similar question in here:
Include another HTML file in a HTML file
This can solve my problem. However, it is a little different from what I want. It is loading another html in an html file but I am looking for extending another html; I mean adding to another base.html and having a new html file
It looks like you're using the Django Templating Language which is similar to Jinja (I've only used this one because I've mostly used Flask but the way it works should be similar). Django uses this language in its template engine and the way it works is by basically taking your HTML file, passing it through a backend (Django), and replacing the variables/logic you have there with actual values. In the end, you'll have a fully built HTML file.
The short answer is no.
From my understanding of template engines, you need to have a backend that can actually work out which values (by replacing this syntax { some_variable }) you should put in the final HTML output.
I have a problem using a js library with django. I am trying to use the particle.js library to generate a particle background for the home page and I have tried following this tutorial.
I have created a particle.json and style.css in my static folder.
UPDATED VERSION (with static files)
home.html
<!-- templates/home.html -->
{% load socialaccount %}
{% load account %}
{% load static %}
<head>
<link rel="stylesheet" href="{% static 'style.css' %}"> </head>
<body>
<div id="particles-js">
{% if user.is_authenticated %}
<p>Welcome {{ user.username }} !!!</p>
<a href="/accounts/logout/" >Logout</a>
{% else %}
Log In with Github
Log In with Twitter
Log In with Facebook
Log In with LinkedIn
{% endif %}
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.2/particles.min.js"></script>
<script>
particlesJS.load('particles-js', '{% static 'particles.json' %}', function(){
console.log('particles.json loaded...');
});
</script> </body>
defined the static path in settings.py
STATIC_URL = '/static/'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'artemis/static')
]
and im my urls.py file
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('accounts/', include('allauth.urls')),
url('', views.Home.as_view(), name='home'),
] + static(settings.STATIC_URL)
When i start the server, I get the following errors in the console:
GET http://127.0.0.1:8000/static/ net::ERR_ABORTED
Uncaught ReferenceError: particlesJS is not defined
The project structure:
I just started learning django so I know this might sound like a stupid question but any idea what might be going wrong here?
Django can not parse the remainder:
{% static style.css %} this should be {% static 'style.css' %} with quotes
{% static particles.json %} should be {% static 'particles.json' %} with quotes
I am using Twig as my template, utilizing a layout, in which I have a javascript block
...
{% block javascripts %}
{% javascripts
'#jquery'
'#bootstrap_js' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
</body>
In a content template, I have
{% block javascripts %}
{{ parent() }}
{% javascripts '#AppBundle/Resources/public/index/*' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
This is my assetic section of the config.yml
assetic:
debug: true
use_controller: false
filters:
cssrewrite: ~
assets:
bootstrap_js:
inputs:
- %kernel.root_dir%/../vendor/twbs/bootstrap/dist/js/bootstrap.min.js
bootstrap_css:
inputs:
- %kernel.root_dir%/../vendor/twbs/bootstrap/dist/css/bootstrap.css
- %kernel.root_dir%/../vendor/twbs/bootstrap/dist/css/bootstrap-theme.css
filters:
[cssrewrite]
bootstrap_glyphicons_ttf:
inputs:
- %kernel.root_dir%/../vendor/twbs/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf
output:
"../fonts/glyphicons-halflings-regular.ttf"
bootstrap_glyphicons_eot:
inputs:
- %kernel.root_dir%/../vendor/twbs/bootstrap/dist/fonts/glyphicons-halflings-regular.eot
output:
"../fonts/glyphicons-halflings-regular.eot"
bootstrap_glyphicons_svg:
inputs:
- %kernel.root_dir%/../vendor/twbs/bootstrap/dist/fonts/glyphicons-halflings-regular.svg
output:
"../fonts/glyphicons-halflings-regular.svg"
bootstrap_glyphicons_woff:
inputs:
- %kernel.root_dir%/../vendor/twbs/bootstrap/dist/fonts/glyphicons-halflings-regular.woff
output:
"../fonts/glyphicons-halflings-regular.woff"
jquery:
inputs:
- %kernel.root_dir%/../vendor/components/jquery/jquery.min.js
Everything else works fine, except for the files under #AppBundle/Resources/public/index/*. I run assetic:dump for my environment, everything goes smoothly, but I keep getting a 404 HTML dump underneath the script element for #AppBundle/Resources/public/index/*
<script src="/logbook/web/js/431d650.js">
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>An Error Occurred: Not Found</title>
</head>
<body>
<h1>Oops! An Error Occurred</h1>
<h2>The server returned a "404 Not Found".</h2>
<div>
Something is broken. Please let us know what you were doing when this error occurred.
We will fix it as soon as possible. Sorry for any inconvenience caused.
</div>
</body>
</html>
</script>
Something is broken, apparently, but I cannot figure out what???
I did also have some issues using assetic in the past and I wrote down a way how I got it work. Maybe it would help you if you'd try to execute the following command first before dumping the assetic stuff:
php app/console assets:install --symlink web