How do I avoid having to use isset() in Laravel Blade templates? - laravel-blade

I've got a Blade file like this:
<a href="{{ $url }}" class="{{ $wrapperClass }}">
<p class="{{ $paraClass }}">{{ $title }}</p>
</a>
And call it like this:
<x-mycomponent
url="{{ $book->url }}"
title={{ $book->title }}
wrapper-class=""
para-class = ""
/>
Works great, but whenever I want to add a variable to the component, I need to add this to each file where I call this component.
How can I write it without having to specify all variables and without having to use isset() or {{ $myvar ?? '' }} in Blade? like this:
<x-mycomponent
url="{{ $book->url }}"
title={{ $book->title }}
/>

You can assign default values for your properties like the below's peace of code:
#props([
"product" => null
])
{{ $product }}
and then, you can call your component in both these ways:
<x-mycomponent />
<x-mycomponent product="$product" />
Note: #props is a Blade directive that allows you to pass data from a parent component to a child component.

Related

Hugo: How to set dict value by interpolation?

In Go (Hugo) templates, how can I set the value of a single entry in a dict?
In this example, I start with a pre-populated dict $vitality and maybe a string .Params.vitality. If the string has anything, I'd like to set the dict entry that the string is the key to to 1.
<figure class="histogram">
{{ $vitality := (dict
"institutional" .Params.count_institutional
"stable" .Params.count_stable
"endangered" .Params.count_endangered
"dying" .Params.count_dying
"extinct" .Params.count_extinct)
}}
{{ if ne .Params.vitality "" }}
{{ $vitality.(.Params.vitality) <!--problem line-->
:= .Params.vitality
}}
{{ end }}
{{ range $key, $value := $vitality }}
<div class="histogram-bar"
data-category="{{ $key }}"
data-count="{{ $value }}">
<div class="histogram-bar-label">{{ $key }}</div>
</div>
{{ end }}
</figure>
This doesn't parse, with Hugo choking on the first . in $vitality.(.Params.vitality). I believe this attempt is called interpolation, and the goal isn't possible without interpolation. Is it possible in Go templates, and if so, how?
It appears you are wanting to add .Params.vitality to the $vitality dict. I think what you want is merge. Your problem line becomes.
$vitality = merge $vitality(dict "vitality" .Params.vitality)

Is it possible to pass twig variables into templates?

I'm using the Timber plugin for my Wordpress site. For a little button component, i'm trying to pass the variable {{ site.link }} to use as my href.
Like so:
{% include 'component/icon-button.twig' with { href: '{{ site.theme.link }}/faq' } %}
icon-button.twig
<button class="icon-button" data-href="{{ href }}">text</button>
But that only results in {{ site.link }}/faq being output as is, as a string, not the actual URL.
How would i do this?
That's just because when you use include in twig you don't need to use double {{ again. The correct syntax would be:
{% include 'component/icon-button.twig' with { href: site.theme.link ~ '/faq' } %}
The "~" is used for string concatenation in twig. You were passing the whole thing as a string and nothing more =)

Use LiipImagineBundle without filters

I'm using LiipImagineBundle in my Symfony2 project and everything is working great. I've defined a thumbnail filter:
<img src="{{ 'bundles/app/images/home/warning.jpg'|imagine_filter('thumb_home') }}" alt="Warning" />
And it works perfectly, but some of my images don't need any filter, so I've tried to remove the filter:
<img src="{{ 'bundles/app/images/home/warning.jpg'|imagine_filter('') }}" alt="Warning" />
<img src="{{ 'bundles/app/images/home/warning.jpg'|imagine_filter() }}" alt="Warning" />
**edited to correct the example as malcolm points out
But it doesn't work, so I need to use Assetic for these images:
{% image '#AppBundle/Resources/public/images/example.jpg' %}
<img src="{{ asset_url }}" alt="Example" />
{% endimage %}
I can't find in the documentation of the bundle any option which allows me to use the Bundle without filters. Is that true? Of course, I can use the LiipImagineBundle way to include images when they need a filter and the Assetic way when they don't, but switching between two different ways of achieving almost the same thing is pretty annoying.
Silly answer to your question - create an original size filter then :). Something like this:
class OriginalSizeFilter implements LoaderInterface
{
public function load(ImageInterface $image, array $options = [])
{
$size = $image->getSize();
$origWidth = $size->getWidth();
$origHeight = $size->getHeight();
$filter = new Thumbnail(new Box($origWidth, $origHeight));
$image = $filter->apply($image);
return $image;
}
}
service:
original_size_filter:
class: ...\OriginalSizeFilter
tags:
- { name: liip_imagine.filter.loader, loader: original_size_filter }
config.yml:
filter_sets:
original:
filters:
original_size_filter: ~
Usage:
<img src="{{ 'bundles/app/images/home/warning.jpg'|imagine_filter('original') }}" alt="Warning" />
But, why not use a asset() function if you don't want any filters to be applied?

How to get the absolute path of a file in a Symfony2 controller?

I want to send an email with an attachement so therefore I need the absolute path to the pdf file.
I tried the flowing code in the controller:
$this->get('templating.helper.assets')->getUrl('MyDoc.pdf', 'doc');
But this returns:
/bundles/MyBundle/doc/MyDoc.pdf?v=1
This is the path without the domain for web access. But I need the real path starting the root of the disk, like example below. How is this possible? Thanks.
/home/MyAccount/public_html/web/src/company/MyBundle/Resources/public/doc/MyDoc.pdf
$this->get('templating.helper.assets') asset helper is about HTTP URI, not directory path.
However, you can easily get the right absolute directory web path like this:
$appPath = $this->container->getParameter('kernel.root_dir');
$webPath = realpath($appPath . '/../web');
$webPath should return something like this:
/home/martins/www/symfony-project/web
A bit of a cheat sheet for anyone else looking for different URL/URI paths for different applications.
Using the Symfony\Component\HttpFoundation\Request component, there are lots of different ways you can call upon this.
Consider this link http://dev.col.com/app_dev.php/my-route?bar=1&foo=bar
$r = $this->getRequest();
$r->getClientIp() 127.0.0.1
$r->getScriptName() /app_dev.php
$r->getPathInfo() /my-route
$r->getBasePath() ''
$r->getBaseUrl() /app_dev.php
$r->getScheme() http
$r->getPort() 80
$r->getHttpHost() dev.col.com
$r->getRequestUri() /app_dev.php/my-route?bar=1&foo=bar
$r->getBaseServerUrl() http://dev.col.com
$r->getUri() http://dev.col.com/app_dev.php/my-route?bar=1&foo=bar
$r->getUriForPath("/other-path") http://dev.col.com/app_dev.php/other-path
$r->getQueryString() bar=1&foo=bar
$r->isSecure() false
$r->getHost() dev.col.com
$r->getMethod() GET
$r->isXmlHttpRequest() false
Or you can do it in Twig as well. For example:
<div>
<a href="{{ job.url }}">
<img src="{{ app.request.scheme ~ '://' ~ app.request.host }}{{ asset(job.webPath) }}" alt="{{ job.company }} logo" />
</a>
</div>
<div>
<a href="{{ job.url }}">
<img src="{{ app.baseServerUrl }}{{ asset(job.webPath) }}"alt="{{ job.company }} logo" />
</a>
</div>
use Symfony\Component\Finder\Finder;
$finder = new Finder();
$finder->files()->in("dir")->name("name.file");
foreach ($finder as $file) {
// Dump the absolute path
var_dump($file->getRealPath());
}
From Docs: http://symfony.com/doc/current/components/finder.html

Adding a CSS class to fields in django.contrib.auth.views.login

I'm still fairly new to django, and have come across Django forms for the first time through my use of the django.contrib.auth.views.login view, used when Django needs a user to authenticate.
I cannot however figure out how to add a CSS class to the username and password fields and the documentation doesn't specify how I can achieve it. Ideally I'd like to simply add the additional info to the template tag, such as {{ form.username | class="usernameclass" }} or whatever, or even write the field out manually, such as <input type="{{ form.password.type }}" name="{{ form.password.name }}" class="form-field-password"/>, but if I need to add a custom view to achieve this I can try that way.
The files related to this are below:
templates/login.html:
{% load url from future %}
...
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<span class="heading">{{ form.username.label_tag }}</span><br/>
{{ form.username }}<br/>
<span class="heading">{{ form.password.label_tag }}</span><br/>
{{ form.password }}<br/>
<div id="login-button">
<input type="submit" value="Log In" />
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
...
settings.py:
...
LOGIN_URL = '/login/'
...
urls.py
...
urlpatterns = patterns('',
url(r'^$', 'portal.views.home', name='home'),
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
url(r'^logout/$', 'django.contrib.auth.views.logout'),
...
)
Any advice is much appreciated!
This app will do exactly what you need.

Resources