Output page is parsed as XML in a browser - symfony

At first, I saw a topic Symfony Twig and xml - Document is empty error and my case is similar, but provided answers there, did not help me.
So my problem is: sometimes I got parsing error in a browser.
In chrome it is:
This page contains the following errors:
error on line 38 at column 21: Opening and ending tag mismatch: link line 19 and head
Below is a rendering of the page up to the first error.
But on firefox things get a little bit more accurate? (I got non-english version so here is my translation of this error):
Error parsing XML: wrong tag. Expected </link>
So my guess is, Symfony somehow provide XML document to the browser, instead of HTML.
But looking at the source code, or even at Inspector, there is nothing that would indicate XML. I got <!DOCTYPE html> tag at start, and proper tags.
When this error occur document in Inspector in Chrome is parsed, like <LINK> tags should have end tags (</LINK>) and everything under this tag is considered as be inside this <LINK> tag. But message in Firefox gave me answer: XML document, so <LINK> tag is treated like tag with closure.
But what is more important, this happening only sometimes, not always. For most of the time I got good looking website, with everything working, all tags parsed, all assets loaded, Javascripts working well.
Why this could happen that sometimes, Symfony put XML file instead of HTML to a browser?
I have an idea, that this could be because of HTTP-CACHE I have inserted in my app in the controller action. Maybe I configured something in a wrong way.
Or maybe there is something else wrong in here? Maybe in other YAML configuration file?
public function index()
{
$categories = [ ... ];
$articlesByCategory = [ ... ]; // is readed correctly - checked
return CacheService::buildCachedResponse($this->render('pages/home.html.twig', [
'categories' => $categories,
'articles' => $articlesByCategory,
...
]), self::CACHE_TIME);
}
class CacheService
{
public static function buildCachedResponse(Response $response, int $expirationSeconds)
{
$response->setPublic();
$response->setMaxAge($expirationSeconds);
$response->headers->addCacheControlDirective('must-revalidate', true);
return $response;
}
}
class CacheKernel extends HttpCache
{
protected function getOptions(): array
{
return [
'default_ttl' => HttpCacheTimesPerController::DEFAULT,
];
}
}
Kernel switched to "CacheKernel" in "public/index.php", as showed in Symfony documentation.
INFO: currently app is running on symfony 5.x, and php 7.4.

Related

I can't get my subrouter to work properly

I have a router like so
r := mux.NewRouter()
    r.PathPrefix("/static/styles/").Handler(http.StripPrefix("/static/styles/",
        http.FileServer(http.Dir("static/styles"))))
book := r.PathPrefix("/books").Subrouter()
    book.HandleFunc("/issued-books/", IssuedBooks)
    book.HandleFunc("/top-trending/", ShowTopTrending)
    book.HandleFunc("/", ShowAllBooks)
    book.HandleFunc("/available/", ShowAvailable)
    r.HandleFunc("/", ShowHome)
    http.ListenAndServe(":8080", r)
The basic handler function structure is below:
func ShowAvailable(w http.ResponseWriter, r *http.Request) {
    tmp := Store{}
for ix, val := range JSON.Books {
         status := &val.IssueStatus
if *status == false {
             tmp.Books = append(tmp.Books, JSON.Books[ix])
}
}
renderTemplate(&w, "available.html", &tmp)
}
renderTemplate is defined like so :
func renderTempate(w *http.ResponseWriter, filename string, tmp *Store) {
    path := "static/" + filename
    tmpl := template.Must(template.ParseFiles(path))
    buf := new(bytes.Buffer)
if err := tmpl.ExecuteTemplate(buf, filename, *tmp); err != nil {
         http.Error(*w, err.Error(), http.StatusInternalServerError)
return
}
mime.AddExtensionType(".css", "text/css; charset=utf-8")
    res := *w
    res.Write(buf.Bytes())
    res.(http.Flusher).Flush()
}
The first Issue is it never renders the css file correctly....the browser always ends up saying ....
Refused to apply style sheet from /path/to/css.... because its MIME type ('text/plain') is not a supported stylesheet MIME type....and i tried using the MIME package to set it correctly just before sending the processed template to the client but it still wont work.
The Second Issue is the HTML rendering becomes inconsistent....only the ShowAllBooks page displayed, others didn't,
giving a 404 error...for this i tried removing the forward slash from the URL paths and it all pages displayed...so the forward slash affects the page rendering...any help is deeply appreciated
Remove ending slashed for routes:
book.HandleFunc("/issued-books", IssuedBooks)
book.HandleFunc("/top-trending", ShowTopTrending)
book.HandleFunc("/", ShowAllBooks)
book.HandleFunc("/available", ShowAvailable)
css is supported by GO out of the box - https://github.com/golang/go/blob/master/src/mime/type.go#L60
Check what exactly server returns for for css links. Could it be 404?

DataTables editable (where to put the editable_ajax.php file)

I'm trying to edit my tables content by following this example DataTables example
In my twig page I've added this script at the end:
$(document).ready(function() {
/* Init DataTables */
var oTable = $('.dataTable').dataTable();
/* Apply the jEditable handlers to the table */
oTable.$('td').editable( 'editable_ajax.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
"height": "auto",
"width": "auto"
} );
} );
the file editable_ajax.php is in the folder where my twig page is.
When I try to edit a cell I see with the debugging tool that the 'editable_ajax.php' file is not found, Can someone tell me where I should place it please ?
I'm sorry to say, but you seem to not have a good grasp of how templating and Symfony in general work. You're mixing very different things (PHP code, twig templates, Javascript code).
So, first read the Symfony Book. I would also suggest reading up on Javascript.
Some mistakes:
PHP files should never be in the "views" folder (aka. with twig files)
Javascript runs on the client side so you need to think about URLs when calling server-side code (aka. php code) NOT filesystem paths.
Javascript (jQuery is just a library) should not be in a twig file, but it's own *.js file and linked with a <script> html tag.

Solution for SAPUI5 error message because of templateShareable:true?

Since an upgrade of SAPUI5 1.28.20 I receive the following error message:
A shared template must be marked with templateShareable:true in the
binding info
Code is in MangedObject.js and looks like this:
} else if ( oBindingInfo.templateShareable === MAYBE_SHAREABLE_OR_NOT ) {
// a 'clone' operation implies sharing the template (if templateShareable is not set to false)
oBindingInfo.templateShareable = oCloneBindingInfo.templateShareable = true;
jQuery.sap.log.error("A shared template must be marked with templateShareable:true in the binding info");
}
Value of oBindingInfo.templateShareable is true, value of MAYBE_SHAREABLE_OR_NOT is 1.
According to documentation the default of oBindingInfo.templateShareable is true.
So what is wrong here? A bug in the library? Or something with my code?
See also: https://sapui5.netweaver.ondemand.com/sdk/#docs/api/symbols/sap.ui.base.ManagedObject.html
Update for SAPUI5 version 1.32.x
With version 1.32.x the message has changed it is now:
A template was reused in a binding, but was already marked as
candidate for destroy. You better should declare such a usage with
templateShareable:true in the binding configuration. -
but according to the documentation the default should still be true:
{boolean} oBindingInfo.templateShareable?, Default: true option to
enable that the template will be shared which means that it won't be
destroyed or cloned automatically
Now it looks like, that this produces some endless loading, I got this message again and again till the browser crashes.
Anyone an idea what could be wrong?
Looks like the message occurs if the template was instantiated outside the binding. Example:
This code will work:
new sap.m.Select({
items : {
path : "/Items",
template : new sap.ui.core.Item({
text : "{Name}"
})
}
})
This code seems to produce the message:
var oTemplate = new sap.ui.core.Item({
text : "{Name}"
})
new sap.m.Select({
items : {
path : "/Items",
template :oTemplate
}
})
This seems to fix the problem:
var oTemplate = new sap.ui.core.Item({
text : "{Name}"
})
new sap.m.Select({
items : {
path : "/Items",
template :oTemplate,
templateShareable : true
}
})
The answer above marked as being correct is actually not correct at all because this here is wrong:
Looks like the message occurs if the template was instantiated outside
the binding. [...] This code seems to produce the message: [...]
To prove the answer above os wrong on your own just run this example (SAPUI5 1.28.20 has the same result):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SAPUI5 single file template | nabisoft</title>
<script
src="https://openui5.hana.ondemand.com/1.36.12/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="async"></script>
<!-- use "sync" or change the code below if you have issues -->
<script>
sap.ui.getCore().attachInit(function () {
"use strict";
var oModel = new sap.ui.model.json.JSONModel({
Items: [
{Name: "Michael"},
{Name: "John"},
{Name: "Frank"},
{Name: "Jane"}
]
});
sap.ui.getCore().setModel(oModel);
var oTemplate = new sap.ui.core.Item({
text : "{Name}"
});
new sap.m.Select({
items : {
path : "/Items",
template : oTemplate
}
}).placeAt("content");
});
</script>
</head>
<body class="sapUiBody">
<div id="content"></div>
</body>
</html>
Basically, a clear definition of the lifecycle for templates is (or was) missing in UI5. When this issue was detected there were already many older apps around... So now this new "feature" was introduced somewhen last year (which is kind of backwards compatible). UI5 tries to detect automatically the developer's intention about the lifecycle of a given template used in the binding (using some heuristic). If UI5 cannot clearly tell what the developer actually wanted then you will see this error log - which actually does not affect the functionality at all. It just tells the developer that there is a template somewhere which will not be destroyed by the UI5 runtime. In other words, if you set templateShareable=true then you should make sure to destroy the template in order to avoid memory leaks. So just setting templateShareable=true is not the whole story...
I have published a detailed blog about this: Understanding templateShareable in SAPUI5

Meteor - TRIPLE template tag is not allowed in an HTML attribute error

I got error message when trying to run existing meteor project.
$meteor
=> Started proxy.
=> Started MongoDB.
=> Errors prevented startup:
While building the application:
client/coinmx.html:169: TRIPLE template tag is not allowed in an HTML attribute
...title="Totals: {{{get...
^
In Meteor 0.8, it's possible to return a Javascript object which is directly rendered into HTML attributes versus earlier versions, where you had to render it yourself.
Old version:
<input name={{name}} title={{title}}>
helpers:
Template.foo.name = "fooName";
Template.foo.title = "fooTitle";
New version:
<input {{attributes}}>
helpers:
Template.foo.attributes = {
name: "fooName",
title: "fooTitle"
};
All of these can be functions, and reactive, etc. Because the object is rendered directly into attributes, there is no need for you to SafeString some manually rendered content as before. This is the recommended way to go if need to render HTML attributes.
See also the following for how conditional attributes work under this scheme:
https://github.com/meteor/meteor/wiki/Using-Blaze#conditional-attributes-with-no-value-eg-checked-selected
The error is pretty much explanatory: you cannot use {{{something}}} inside a HTML attribute, you need to use {{something}} instead. Depending on what the something is (it's not known from your question as you didn't provide the code), that's either all you need to do, or you can achieve similar functionality by returning new Handlebars.SafeString("result") from your helper instead of just "result". However, if you do, you need to be super sure that the thing you'll return won't break the HTML structure.
Hugo's answer above gave me the missing piece I needed for the same issue-- triple stashes in 0.8 no longer supported. Here is an example that hopefully helps.
Where you might have had {{{resolve}}} in your template, you would now do:
<template name='thing'>
<ol>
{{#each all}}
{{resolve}}
{{/each}}
</ol>
<template>
The helper code then makes use of Spacebars.SafeString which looks to be preferred with Blaze:
Template.thing.helpers({
all: function () {
return Things.find();
},
resolve: function () {
var result = "<li>";
for (var i = 0; i < this.arrayOfClassNames.length; ++i)
result += <'div class='" + this.arrayOfClassNames[i] + "'></div>";
result += "</li>";
return new Spacebars.SafeString(result);
}
});
The key here is to return the 'new Spacebars.SafeString(result)' to wrap your HTML (which must be well formed).

Using Bladejs with Meteor

I recently added the node-blade smart package to my meteor and have static content displaying fine. However, I'm not able to use any template variables. Before I installed blade, the template variables worked fine with handlebars. Does anybody know what I'm doing wrong?
console output
ReferenceError: player is not defined
at ~/meteor/project/views/info.blade:1:1
1 > .player-name.large= player.name
2 | .alliance-name= alliance.name
3 | .world-name= world.name
4 |
at eval (eval at <anonymous> (/usr/local/lib/node_modules/blade/lib/compiler.js:138:23))
at /usr/local/lib/node_modules/blade/lib/runtime.js:323:5
at runtime.loadTemplate (/usr/local/lib/node_modules/blade/lib/runtime.js:272:6)
at /usr/local/lib/node_modules/blade/lib/blade.js:45:4
at Compiler.compile (/usr/local/lib/node_modules/blade/lib/compiler.js:185:2)
at compile (/usr/local/lib/node_modules/blade/lib/blade.js:41:12)
at Object.compileFile (/usr/local/lib/node_modules/blade/lib/blade.js:66:3)
at Object.runtime.loadTemplate (/usr/local/lib/node_modules/blade/lib/runtime.js:269:23)
at Object.runtime.include (/usr/local/lib/node_modules/blade/lib/runtime.js:320:22)
at eval (eval at <anonymous> (/usr/local/lib/node_modules/blade/lib/compiler.js:138:23))
Your application is crashing. Waiting for file change.
info.blade
.player-name.large= player.name
client.js
if(Meteor.is_client) {
Template.info.player = function(){
var data = Session.get( 'data' );
return data.player;
};
}
EDIT: Helpers are now permitted in body templates.
You cannot use helpers or certain global variables in head or body templates. You can't even use them in templates that are included by head or body templates.
Checkout these links for more information:
https://github.com/bminer/node-blade/issues/98
https://github.com/bminer/node-blade/wiki/Using-Blade-with-Meteor
EDIT: This answer is no longer accurate as of Blade 3.0.0 stable. body.blade templates may not contain dynamic stuff like helpers, references to Session, etc.
In 'Using Blade with Meteor' says that
References to Session are not allowed in head or body templates. This is by design, and it is not a bug. In Handlebars, you could use Session or Meteor within a tag, but not a tag. I didn't like the Handlebars implementation, so you're stuck with this one. The body.blade template is mostly for static content (i.e. a loading page or whatever). Once your application is loaded, you can do $("body").replaceWith(Meteor.ui.render(Template.homepage) ); from your application code.
So, this is saying that, on initialization, one could not have dynamic generated templates.
To workaround this, documentation suggests
$("body").replaceWith(Meteor.ui.render(Template.homepage) )
I replaced replaceWith method with html method. See an example that's working for me:
# ./the_cow.coffee
if Meteor.isClient
$ ->
$('body').html Meteor.render -> Template.test
user:
name: 'Pill'
# ./views/test.blade
#test Testing
p= user.name
See the compiled JavaScript:
if (Meteor.isClient) {
$(function() {
return $('body').html(Meteor.render(function() {
return Template.test({
user: {
name: 'Pill'
}
});
}));
});
}
Don't know if there is a shorter way to write it.

Resources