[SOLVED] Twig error with routing with an argument

Hello!

I’m kinda new in web programming and at using frameworks. I have a small problem by getting an error when I put a getter on a page with an argument. The odd thing is that actually works, but I still get an error when I’m not on this page.

The error is the following :

Message: An exception has been thrown during the rendering of a template (“Missing data for URL segment: userprofile”) in “layout.twig” at line 19.

And here’s the precise case:

I did the basic routing with an argument like this :

projectname/profile/foo

to get something like this:

Hello foo

So here’s how I did it:

From the index.php I got the get for the profile page:

$app->get('/profile/{userprofile}', 'App\Controllers\PagesController:getProfile')->setName('user.profile');

My getProfile function (I made a render function to avoid writing $this->container->view->[…] ):

public function getProfile($request, $response, $args) {
	$userprofile = $args['userprofile'];

	return $this->render($response, 'pages/profile.twig',[
	'userprofile' => $userprofile
	]);
	}

Here’s my profile.twig file:

{% block content %}
Hello {{userprofile}}
{% endblock %}

Here’s my layout.twig:

<li><a href="{{ path_for('user.profile') }}"><span class="glyphicon glyphicon-user"></span> Profile</a></li>

So again, it WORKS when I’m in this page, but get the twig error outside of this page. (Excepted on /profile without arguments, where I get a classic Page not found error).
Did I missed something? (Probably yes, but what? :smiley:).
Thanks for your time!

What does your layout.twig file look like? Specifically, around line 19. I would assume you are building a path_for and not passing it the value for a non-optional segment.

1 Like

Hello, I just noticed that I missed a crucial information, from where the problem comes :expressionless: , sorry for that.

Indeed, I didn’t mentionned my “layout.twig”, which contains my navbar, with a link to the logged user’s profile.

Here it is:

<li><a href="{{ path_for('user.profile') }}"><span class="glyphicon glyphicon-user"></span> Profile</a></li>

I guess the problem definitely comes from that.

I’ll try to fix that finding the right syntax to mix the user profile path (/profile/) with an other variable for the username (/foo).

Also I’ll update the OP.

Thanks for your help! And sorry for forgetting the main element.

Yes, that is it. You will want something like this.

<li><a href="{{ path_for('user.profile', { 'userprofile': userprofile }) }}"><span class="glyphicon glyphicon-user"></span> Profile</a></li>
1 Like

Ah wonderful! It works! (I set username to user.name which is the current logged user’s name).
I thought I had checked all the steps, but now I see that the problem was obvious.

Thanks for the help and your time!

1 Like