Silex & Twig helpers in custom error pages - url

I'm struggling with a problem while trying to render a custom error page in Silex.
According to what I found in this link :http://refactoring.us/silex/custom-error-pages-with-silex-and-twig/
I am trying to set up a custom 404 error page in my application. Everything works fine until I start to use helpers in my twig template.
An exemplary code for 404 error page template is as follows :
{% extends "layout.html.twig" %}
{% block main %}
<div id="error404">
<h2>{{ app.translator.trans('page404.title') }}</h2>
<p>{{ app.translator.trans('page404.para1') }}</p>
<p class="btn-footer">
{{ app.translator.trans('page404.button') }}
</p>
</div>
{% endblock %}
PHP code for error handling in my Silex app:
$app->error(function (\Exception $e, $code) use($app) {
switch ($code) {
case 404:
$message = $app['twig']->render('error404.html.twig');
break;
default:
$message = $app['twig']->render('error500.html.twig');
}
return new Response($message, $code);
});
Once i remove {{ url('home') }} (this helper and route works perfectly in other cases!) I get the proper rendered site, but without the translations.
With the helper, I get the following error:
Fatal error: Uncaught exception 'Symfony\Component\Routing\Exception\RouteNotFoundException' with message 'Route "" does not exist.' in D:\projects\projectname\application\vendor\symfony\routing\Symfony\Component\Routing\Generator\UrlGenerator.php:119 Stack trace:
#0 D:\projects\projectname\application\vendor\symfony\twig-bridge\Symfony\Bridge\Twig\Extension\RoutingExtension.php(45): Symfony\Component\Routing\Generator\UrlGenerator->generate(NULL, Array, false)
#1 D:\projects\projectname\application\vendor\twig\twig\lib\Twig\Environment.php(327) : eval()'d code(68): Symfony\Bridge\Twig\Extension\RoutingExtension->getPath(NULL, Array)
#2 D:\projects\projectname\application\vendor\twig\twig\lib\Twig\Template.php(265): __TwigTemplate_ca53e56b87abd45da5c34a79d4c2ce34->doDisplay(Array, Array)
#3 D:\projects\projectname\application\vendor\twig\twig\lib\Twig\Template.php(239): Twig_Template->displayWithErrorHandling(Array, Array)
#4 D:\projects\projectname\application\vendor\twig\twig\lib\Twig\Envir in D:\projects\projectname\application\vendor\twig\twig\lib\Twig\Template.php on line 280
So I need some guidance here on what could be the possible reason behind this that is causing this and steps to resolve this issue. All help appreciated.

This is not a Silex problem (as of now) - Everything works perfectly on my side (Silex 1.2)
Did you register the UrlGeneratorServiceProvider in your app ?
in web/index.php:
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
And you should really use path() instead of url()in this case :
{{ path('home') }}

Related

django-channels websocketbridge error

I am pretty new to django-channels.
while trying to set websocketbridge I ran into an errorin my JS:
Uncaught ReferenceError: channels is not defined
I loaded websocketbridge.js on top of my html template:
% load staticfiles %}
{% static "channels/js/websocketbridge.js" %}
and in my JS I have tried both:
const webSocketBridge = new channels.WebSocketBridge(); // try 1
const webSocketBridge = new WebSocketBridge(); // try 2
which are raising a similar error. What I am missing?
I solved this one pretty quick but I am leaving a solution for beginners like me who might find themselves into the same problem.
In my case, I am just handling the static files a bit differently so I just changed
{% static "channels/js/websocketbridge.js" %}
on top of my html template to
<script type="text/javascript" src="{% static '/channels/js/websocketbridge.js' %}"></script>
at the bottom of the template body, where I load specific static files and other js scripts.
Hope that helps.

How to define ruby code inside a haml file present in javascript folder

For my project, I am using Ruby on Rails and Angular and I have a haml file present in /project_name/app/assets/javascript folder. I want to call a ruby class from the haml file but unfortunately I am not able to do that.
.small-12.columns
.booking-time
%span.bold
- if ABC::D.data(:hide_hours_field) #ruby code
{{ item | timeformat }}
- else
{{ item | differentTimeFormat }}
Whenever I start the server, it's is showing it can't access the ruby class. I can easily access the ruby class in other haml files but not the one present in javascript folder. Can anyone help me here?
Disclaimer: I'm bad at Angular (and didn't even touch version 2). What follows is not a best practice or anything.
So, you need to configure your angular view with some knowledge from ruby side. You can't conditionally render it and you can't call ruby from angular controllers (obviously). I suggest smuggling data via window object.
In an appropriate view in your application, put this JS snippet.
<script type='text/javascript'>
window.jsEnv = {
hide_hours_field: <%= ABC::D.data[:hide_hours_field] %>
}
</script>
Then you can reference that via $window object in angular
Controller
function MyController($window) {
this.hideHours = function() {
return !!$window.jsEnv.hide_hours_field;
}
}
MyController.$inject = ['$window'];
angular.module('myApp').controller('MyController', MyController);
View
.small-12.columns(ng-controller='MyController as vm')
.booking-time
%span.bold(ng-if='vm.hideHours()')
{{ item | timeformat }}
%span.bold(ng-unless='vm.hideHours()')
{{ item | differentTimeFormat }}
I suggest you use angular constant instead of window then you can use it as service:
// index.html
<script type="text/javascript">
angular.module('myApp').constant('CURRENT_USER', #{current_user.to_json})
</script>
// controller
function ApiConsoleController($scope, CURRENT_USER) {
console.debug(CURRENT_USER)
}
Also, you can try to use angular-rails-templates
// application.rb
config.angular_templates.ignore_prefix = %w(
angular/components/
angular/shared/
angular/directives/
angular/validators/
)

October CMS how to get current locale name?

Could you tell me please how i can get current language name or somthing like this.
I want customize Locale Switcher on web site based on October CMS.
It will be greate to recevie something like
...
{{ set var = ****.getLocale();}}
...
then use it for switch($var){}
...
In twig you can access the current language with {{ activeLocale }}, the full language name with {{ activeLocaleName }} and an array with all locales available with {{ locales }}.
You could use {{ dump() }} to see all variables available on a page. If you try it you will find the locale variables right there as well.
i tried with activeLocale and also with locales array but one can not stop the loop and thus it was impossible for me to render some content conditionally. this is how i solved it, after reading the logic of plugin that how it is working, I did this in one of my partials.
==
use RainLab\Translate\Classes\Translator;
protected $translator;
function onStart()
{
$this->translator = Translator::instance();
$this['SelectedLanguage'] = $this->activeLocale = $this->translator->getLocale();
}
==
{% set CurrentLanguage = SelectedLanguage %}
now {{CurrentLanguage}} will give me code for current language so now using twig i can do some conditional rendering like this
{% if CurrentLanguage is same as('en') %}{% endif %}
{% if CurrentLanguage is same as('tr') %}{% endif %}
{% if CurrentLanguage is same as('gr') %}{% endif %}
Maybe there could be a another solution. but this one worked like charm.
Update:
Although, In case of components or elsewhere one can use session to retrieve the current language this way,
Session::get('rainlab.translate.locale')
Assuming that you use RainLab.Translate plugin?
Create a partial that uses the localePicker component and then use your custom code:
<div>{{ activeLocale }} - {{ activeLocaleName }}</div>
{% for code, name in localePicker.locales %}
<div>{{ code }} - {{ name }}</div>
{% endfor %}
And just call that partial from where you want to use it.

Chicago Boss CSRF and variable passing to template files

I've two problems with my simple application.
I've read the documents twice, but had no luck to using boss_csrf_filter and passing variables to templates.
First I've done the configuration for using CSRF filter in boss.config file as the following :
{controller_filter_config, [boss_csrf_filter]},
{session_adapter, mock},
{session_key, "_myapp_session"},
{session_exp_time, 525600},
{session_cookie_http_only, false},
{session_cookie_secure, false},
{session_domain, ".myappdomain.com"},
Then, I've add to variable in template (which is under src/view/world/hello.html)
<div class="row">
<div class="12u">
<textarea name="message" id="message" placeholder="placeholder" required></textarea>
{{ csrf_token }}
</div>
</div>
Everthing seems fine, but no any hidden input element appearing. Should I check/configure anything else?
The second problem is with my app is passing variables to templates. My is controller something like the following code :
-module(myapp_world_controller, [Req]).
-compile(export_all).
hello('GET', []) ->
{ok, [{world}]}.
postcontact('POST', []) ->
{redirect, "/",[{contactformsend, "ok"}]}.
The code is redirecting without any value. So, the following code is not working (the same template file with I've mentioned above) :
{% if contactformsend %}
<script>
alert("Hi there is!");
</script>
{% endif %}
What I am doing wrong? How can I fix the problems?
I would propose to split your question into two, because I have answer only for the second part. When you use redirect in controller, you don't pass the variables. In the docs you can read this:
{redirect, Location, Headers::proplist()}
So the third argument is list of headers, not variables passed to templates. It makes sense: the variables will be taken from the controller, that is responsible for rendering "/".

Jquery Ajax & Microsoft JScript runtime error: Syntax error, unrecognized expression:

I am working on the ode-to-food MVC4 demo app on Pluralsite by Scott Allen and have a troublesome error enabling ajax calls. I am thinking this may have something to do with my more recent jquery version but not sure.
When I uncomment following line to activate ajax call I get the Microsoft JScript runtime error, otherwise it works fine:
$('form[data-ucw-ajax="true"]').submit(ajaxFormSubmit);
The error is:
Unhandled exception at line 4411, column 2 in http://localhost:17471/Scripts/jquery-1.9.0.js
0x800a139e - Microsoft JScript runtime error: Syntax error, unrecognized expression:
<div class="wrapper clearfix">
....
</div>
<hr />
My View has this form:
<form method="get" action="#Url.Action("Index")" data-ucw-ajax="true" data-ucw-target="#facilitiesList">
My JQuery code is:
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr('data-ucw-target'));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect('highlight');
});
return false;
};
$('form[data-ucw-ajax="true"]').submit(ajaxFormSubmit);
});
My Script Load Bundles look like:
bundles.Add(new ScriptBundle("~/bundles/jquery/ucw").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*",
"~/Scripts/jquery-migrate-1.0.0.js",
"~/Scripts/My.js"
));
"This" has scope issues. The "this" that you refer to in ajaxFormSubmit is the context of the ajaxFormSubmit , not the click handler of the link. You need to do something like this:
$form = $('form[data-ucw-ajax="true"]');
or give the form an ID and use:
$form = $('#myForm');
Also, I would move Jquery to another bundle to ensure it is loaded before all the other libraries.
I have similar error with another code from that video course - when returned html from partial View wrapped into JQuery to apply animation later...
function dataReceived(data) {
var $newHtml = $(data); -<<<<same Exception here
$(target).replaceWith(data);
$(data).effect("highlight");
}
Exception: Unhandled exception at line 4421, column 2 in jquery-1.9.1.js
0x800a139e - JavaScript runtime error: Syntax error, unrecognized expression:
<div id="restaurantsList">.....
I started with the code from this changeset, then, via NuGet:
updated jQuery to 1.9.1
updated jQuery UI to 1.10.0
added jQuery migrate 1.1.0 (also added to jQuery bundle)
I don't see any problems in Chrome or IE10 (except for JQMigrate warnings). Other than the small difference in jQuery versions, I can't see anything that would be different. Can you try to bump up your jQuery reference? If the problem still persists, send me the error message again with 1.9.1

Resources