I am new with twig and the problem is that when I want to use .twig files it doesn't work same with .html.twig. But when I switch to .html file is working fine. Where is the problem?
EDIT:
index.php:
<?php
use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
require __DIR__.'/../vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('../templates');
$twig = new Twig_Environment($loader, array(
'cache' => '../compilation_cache',
));
$collection = new RouteCollection();
$collection->add('index', new Route('/', array(
)));
// Twig
if (!isset($_SERVER['APP_ENV'])) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('APP_ENV environment variable is not
defined. You need to define environment variables for configuration or
add "symfony/dotenv" as a Composer dependency to load variables from a
.env file.');
}
(new Dotenv())->load(__DIR__.'/../.env');
}
$env = $_SERVER['APP_ENV'] ?? 'dev';
$debug = $_SERVER['APP_DEBUG'] ?? ('prod' !== $env);
if ($debug) {
umask(0000);
Debug::enable();
}
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
Request::setTrustedProxies(explode(',', $trustedProxies),
Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts(explode(',', $trustedHosts));
}
$kernel = new Kernel($env, $debug);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
//Product list TEST TWIG->Delete if not using!
$products = 'products';
$products = array(
array('name' => 'Notebook', 'description' => 'Core i7', 'value' =>
800.00, 'date_register' => '2017-06-22',),
array('name' => 'Mouse', 'description'=> 'Razer', 'value' => 125.00,
'date_register' => '2017-10-25',),
array('name' => 'Keyboard', 'description' => 'Mechanical Keyboard',
'value'=> 250.00, 'date_register' => '2017-06-23',)
);
$template = $twig->load('index.twig');
echo $template->display(array('products' => $products));
index.twig:
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Twig Example</title>
</head>
<body>
<table border="1" style="width: 80%;">
<thead>
<tr>
<td>Product</td>
<td>Description</td>
<td>Value</td>
<td>Date</td>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{ product.name }}</td>
<td>{{ product.description }}</td>
<td>{{ product.value }}</td>
<td>{{ product.date_register|date("m/d/Y") }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
I want to load the array from the index.php file but it throw me error:
Unable to find template "layout.html" (looked into: ../templates) in index.twig at line 1.
I am not using file layout.html anymore the file is deleted. When I refactor index.twig file to index.html it disappears.
EDIT(2):
twig.yaml(/config/packages/twig.yaml):
twig:
paths: ['%kernel.project_dir%/templates']
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
The problem was in the index.php file. When I commented/deleted part:
if (!isset($_SERVER['APP_ENV'])) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('APP_ENV environment variable is not
defined. You need to define environment variables for configuration or
add "symfony/dotenv" as a Composer dependency to load variables from a
.env file.');
}
(new Dotenv())->load(__DIR__.'/../.env');
}
$env = $_SERVER['APP_ENV'] ?? 'dev';
$debug = $_SERVER['APP_DEBUG'] ?? ('prod' !== $env);
if ($debug) {
umask(0000);
Debug::enable();
}
if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
Request::setTrustedProxies(explode(',', $trustedProxies),
Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts(explode(',', $trustedHosts));
}
$kernel = new Kernel($env, $debug);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Everything works fine...
Related
I want to show images from the database in an Excel file downloaded using the Laravel Maatwebsite package.
Controller
$data['company_names'] = Company::where('id', Auth::user()->com_id)
->first(['company_name']);
$data['companies'] = $companies;
$data['users'] = $users;
$data['regions'] = $regions;
$data['roles'] = $roles;
$exl = Excel::download(new EmployeeReportExport($data),
'Employee-Report.xlsx');
ob_end_clean();
return $exl;
Export Code
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
class EmployeeReportExport implements FromView
{
public function __construct($data)
{
$this->data = $data;
}
public function view(): View
{
return view('back-end.premium.hr-reports.employee-report.employee-bulk-report-excel', [
'data' => $this->data
]);
}
}
Blade
<td>{{ $i++ }}</td>
<td>{{ $usersData->company_assigned_id ?? '' }}</td>
<td>{{ $usersData->first_name . ' ' . $usersData->last_name }}</td>
<td><img src="{{ asset($usersData->profile_photo) ?? '' }}" alt=""></td>
<td>{{ $usersData->email ?? null }}</td>
<td>{{ $usersData->phone }}</td>
But it's not showing in the Excel file; it returns the following error.
file_get_contents(http://127.0.0.1:8000/uploads/profile_photos/1667727818.jpg):
failed to open stream: HTTP request failed!
I have an array of elements composed of key => value for example:
arr = { 156 : 'one', 99 : 'tow' }
I want to remove an element from the array depending on the key. Like doing unset() in php ? Is it possible ?
You can also use the filter pipe like this:
{% set arr = arr | filter((v, k) => k != '99') %}
You can extend twig to do this
<?php
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension {
public function getFunctions(){
return [
new \Twig\TwigFunction('unset', [$this, 'unset'], [ 'needs_context' => true, ]),
];
}
/**
* $context is a special array which hold all know variables inside
* If $key is not defined unset the whole variable inside context
* If $key is set test if $context[$variable] is defined if so unset $key inside multidimensional array
**/
public function unset(&$context, $variable, $key = null) {
if ($key === null) unset($context[$variable]);
else{
if (isset($context[$variable])) unset($context[$variable][$key]);
}
}
}
Usage inside twig:
<h1>Unset</h1>
{% set foo = 'bar' %}
{% set bar = { 'foo' : 'bar', } %}
<h2>Before</h2>
<table>
<tr>
<td>foo</td><td>{{ foo | default('not applicable') }}</td>
</tr>
<tr>
<td>bar.foo</td><td>{{ bar.foo | default('not applicable') }}</td>
</tr>
</table>
{% do unset('foo') %}
{% do unset('bar', 'foo') %}
<h2>After</h2>
<table>
<tr>
<td>foo</td><td>{{ foo | default('not applicable') }}</td>
</tr>
<tr>
<td>bar.foo</td><td>{{ bar.foo | default('not applicable') }}</td>
</tr>
</table>
output
Before
|------------------------------|------------------------------|
| foo | bar |
| bar.foo | bar |
|------------------------------|------------------------------|
After
|------------------------------|------------------------------|
| foo | not applicable |
| bar.foo | not applicable |
|------------------------------|------------------------------|
I have been trying to make this work for several days now. I cannot access a profile object from its associated user object. I have the latest versions of Ember and ember-data
Ember-data: 1.0.0-beta15
Ember: 1.10.0 production
I have a simple table view that lists my users and a couple properties. Here is the view:
<script type="text/x-handlebars" data-template-name="users/verification-candidates">
<div class="small-12 column">
<h1>Candidates for Verification</h>
<table>
<tr>
<th>System ID</th>
<th>Email</th>
<th>Created At</th>
<th>Legal First Name</th>
<th>Legal Last Name</th>
<th></th>
<th></th>
</tr>
{{#each user in model itemController="candidate" }}
<tr>
<td> {{ user.id }}</td>
<td> {{ user.email }}</td>
<td>{{ user.created_at }}</td>
<td>{{ user.legal_first_name }}</td>
<td>{{ user.legal_last_name }}</td>
<td><button id="verify" {{ action "markVerified" }}>Verify</button></td>
<td><button id="disable" {{ action "markDisabled" }}>Disable</button></td>
</tr>
{{/each}}
</table>
</div>
</script>
The models are like so:
App.Profile = DS.Model.extend({
user: DS.belongsTo('user'),
incognito_name : DS.attr('string'),
advisor_id : DS.attr('number'),
created_at : DS.attr('date'),
//etc..
App.User = DS.Model.extend({
profile: DS.belongsTo('profile',{ async: true }),
email: DS.attr('string'),
sign_in_count: DS.attr('number'),
last_sign_in_at: DS.attr('date'),
//etc...
I am using the rest adapter:
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:1337',
defaultSerializer: 'json'
});
Pertinent routes:
App.Router.map(function(){
this.resource('users', { path: '/users'}, function(){
this.route('verification-candidates');
});
this.resource('profiles', { path: '/profiles' }, function(){
})
});
App.UsersRoute = Ember.Route.extend({
model: function(){
return this.store.find('user');
}
});
App.ProfilesRoute = Ember.Route.extend({
model: function(){
return this.store.find('profile');
}
})
App.UsersVerificationCandidatesRoute = Ember.Route.extend({
model : function(){
var items = this.store.find('user', { role: "advisor", disabled: false, is_verified: false });
return items;
},
})
My server is a sails.js back end, which accesses a database created by a Rails application.
I want to alter the profile in this object controller, but cannot access it in any meaningful form:
App.CandidateController = Ember.ObjectController.extend({
actions: {
markVerified: function(){
var user = this.get('model');
var profile = user.get('profile');
console.log(profile); //output 1
console.log(profile.incognito_name); //output 2
}
}
});
The output2 is undefined. Output 1 gives me some sort of object with properties __nextSuper, __ember_meta, a bunch of other things, isFulfilled, and content. But, no object properties from the model definition. This appears to be a promisearray,but, I thought this was the way to get a related object. Meanwhile, when I try to treat it as a PromiseArray, per the documentation, i get null, like this:
App.CandidateController = Ember.ObjectController.extend({
actions: {
markVerified: function(){
var user = this.get('model');
user.get('profile').then(function(content){
console.log("promise content is " + content);
//prints 'promise content is null'
})
//console.log(profile);
//console.log(profile.incognito_name);
}
}
I am fairly certain all my back end server/client things are in order, as I can access the user objects and work with them on the page. I am thinking it may be related to how the profile relates to the user via advisor_id, but, I am so confused right now. I am very much at my wit's end.
I am very unfamiliar with twig. Here's what I have:
{% if wp.get_post_meta(post.ID, '_property_website').0 %}
<tr>
<th>{{ wp.__('Website', 'aviators') }}:</th>
<td>{{ wp.get_post_meta(post.ID, '_property_website').0 }}
</td>
</tr>
{% endif %}
I need to restrict this output to 35 characters without killing the link. It needs to still be active but only display 35 characters, plus ideally it would end with... to designate that the url is cut off but that's a bonus. Can anyone help?
I believe http://twig.sensiolabs.org/doc/filters/slice.html is what you are looking for
EDIT
Just found that Twig has an extension called text it includes the wordwrap filter that is exactly what you're looking for
Link: https://github.com/fabpot/Twig-extensions/blob/master/lib/Twig/Extensions/Extension/Text.php
You can make your own Twig Extension. It's very easy.
First you must create the file with the filter code:
<?php
//Acme/AcmeBundle/Twig/AnExtension.php
namespace Acme\AcmeBundle\Twig;
class AnExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('cutText', array($this, 'cutTextFilter'))
);
}
public function cutTextFilter($text, $size = 50)
{
if (strlen($text) > $size)
{
return substr($text, 0, $size) . '...';
}
else
{
return $text;
}
}
public function getName()
{
return 'an_extension';
}
}
Then edit the services.yml file from this bundle, located at: /Acme/AcmeBundle/Resources/config/services.yml and add:
services:
acme.twig.an_extension:
class: Acme\AcmeBundle\Twig\AnExtension
tags:
- { name: twig.extension }
and now you can use the filter in your code:
<a href="http://{{ wp.get_post_meta(post.ID, '_property_website').0 }}">
{{ wp.get_post_meta(post.ID, '_property_website').0 | cutText(30) }}
</a>
More info: http://symfony.com/doc/current/cookbook/templating/twig_extension.html
I had a project with Symfony 2.0 and FOSUserBundle 1.2.0, and everything was working fine. When I upgraded to the latest Symfony 2.1 version and the latest FOSUserBundle from the master branch, after fixing lots of stuff, the labels are not being translated, i.e. "form.username".
I had the User Bundle overwritten by a custom bundle I made. I've overwritten the following stuff:
Controller
ChangePasswordController
GroupController
RegistrationController
UserController
Form
Type
ChangePasswordFormType
RegistrationFormType
Resources
config
routing.yml
views
ChangePassword
changePassword_content.html.twig
changePassword.html.twig
Form
form_group.html.twig
form_user.html.twig
Group
edit.html.twig
list.html.twig
new.html.twig
show.html.twig
Registration
checkEmail.html.twig
email.txt.twig
register_content.html.twig
register.html.twig
User
edit.html.twig
index.html.twig
show.html.twig
I also have a custom user and group entity, and my custom UserType and GroupType which I omitted in the previous tree.
The translation files where at app/Resources/translations/FOSUserBundle.en.yml
I also tryed copying them to my bundle, src/Acme/UserBundle/Resources/translations/FOSUserBundle.en.yml
None of them is working with symfony 2.1.
Of course I cleaned the cache, the production cache, and regenerated assets just in case and refreshed the browser... Everything several times and nothing.
I searched here and on Google and I can't find any clues, I tried some things but without success.
I will copy the contents of some of the files below.
Acme/UserBundle/Controller/RegistrationController.php
<?php
namespace Acme\UserBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
class RegistrationController extends BaseController
{
public function registerAction()
{
$form = $this->container->get('fos_user.registration.form');
$formHandler = $this->container->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
$authUser = false;
if ($confirmationEnabled) {
$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
$authUser = true;
$route = 'AcmeUserBundle_admin_user_index';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$url = $this->container->get('router')->generate($route);
$response = new RedirectResponse($url);
if ($authUser) {
$this->authenticateUser($user, $response);
}
return $response;
}
return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
'form' => $form->createView(),
));
}
}
Acme/UserBundle/Form/Type/RegistrationFormType.php
<?php
namespace Acme\UserBundle\Form\Type;
use Doctrine\ORM\EntityManager;
class RegistrationFormType extends BaseType
{
private $entityManager;
public function __construct($class, EntityManager $entityManager)
{
parent::__construct($class);
$this->entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle', 'error_bubbling' => true))
->add('nombre', 'text', array('error_bubbling' => true))
->add('apellido', 'text', array('error_bubbling' => true))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle', 'error_bubbling' => true))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
'error_bubbling' => true,
))
->add('groups', 'entity', array(
'class' => 'Acme\\UserBundle\\Entity\\Group',
'property' => 'name',
'label' => 'Grupos',
'empty_value' => 'Seleccione Grupos',
'multiple' => true,
'expanded' => true,
'required' => false,
));
}
public function getName()
{
return 'acme_user_registration';
}
}
Acme/Resources/views/Registration/register_content.html.twig
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register">
<div class="content no-padding" {{ block('container_attributes') }}>
{{ form_widget(form) }}
</div>
<div class="actions">
<div class="actions-left" style="margin-top: 8px;"></div>
<div class="actions-right">
<input type="submit" value="{{ 'registration.submit'|trans({}, 'FOSUserBundle') }}" />
</div>
</div>
Acme/Resources/views/Registration/register.html.twig
{% extends "AcmeAdminBundle:Base:base_auth.html.twig" %}
{% form_theme form 'AcmeUserBundle:Form:form_user.html.twig' %}
*[...] Here are stylesheets and JS[...]*
{% block main_content %}
<!-- Start of the main content -->
<div id="main_content">
<h2 class="grid_12">{% block title "Crear Usuario" %}</h2>
<div class="clean"></div>
<div class="grid_6">
<div class="box">
<div class="header">
<img src="{{ asset('bundles/acmeadmin/img/icons/packs/fugue/16x16/ui-text-field-format.png') }}" alt="" width="16"
height="16">
<h3>Información Básica</h3>
<span></span>
</div>
{% block fos_user_content %}
{% include "AcmeUserBundle:Registration:register_content.html.twig" %}
{% endblock fos_user_content %}
</div> <!-- End of .box -->
</div> <!-- End of .grid_6 -->
</div> <!-- End of #main_content -->
<div class="push clear"></div>
{% endblock main_content %}
If I disable my bundle, removing
public function getParent()
{
return 'FOSUserBundle';
}
the labels appear translated as expected. I don't know what else to do. Any Suggestions?