I have a json file with custom data, a list of some game servers. The json file contains the name and other data...
{
"gameServer1": {
"name": "game server",
"ip": "game.gameservers.com",
"port": "25565",
"about": "About this game server",
"nav": {
"navigationLink1": {
"name": "Forum",
"link": "gameserver.com/someurl"
}
}
// etc.. There would be quite a few other servers listed...
}
}
Now, in my HomeController (since this is where the data would be presented) I am pretty lost, all I have is..
public function show()
{
$this->layout->content = View::make('home')->with('servers', $this->getServers());
}
public function getServers(){
$file = file_get_contents(app_path() . '/views/servers.json');
$servers = json_decode($file);
return $servers;
}
And I am pretty sure that's wrong. I just don't know how to do this correctly. What I need to do is pass the properties to my home view
public function show()
{
$this->layout->content = View::make('home')->with($this->getJSON());
}
So I can foreach the results and have something like this presented...
<div class="server">
<h3 class="server-name">{{n $name }}</h3>
<div class="ip-address">
{{ $ipaddress }}
</div><!-- /.ip-address -->
<div class="about-server">
{{ $about }}
</div><!-- /.about-server -->
<div class="server-nav">
<div class="nav-info">
<strong>Quick Links</strong>
</div>
<ul>
<li><a href="">{{links}}</a></li>
</ul>
</div>
etc....
</div><!-- /.server-container -->
I feel like I'm not even close to figuring out how to do this though. What to do?
To pass the data to your view you should give a name in the with
method so using that given name you'll be able to access the data in your view, for example you have following code now:
$this->layout->content = View::make('home')->with($this->getJSON());
You need to pass a name (anything) for the variable like this:
$this->layout->content = View::make('home')->with('servers', $this->getJSON());
Now you can access the data in your view by referring the $servers
variable. Since your $servers
variable will contain an array of stdClass
so you may loop the $servers
variable in the view like this:
<div class="server">
@foreach($servers as $server)
<h3 class="server-name">{{ $server->name }}</h3>
<div class="ip-address">
{{ $server->ip }}
</div>
<div class="about-server">
{{ $server->about }}
</div>
<div class="server-nav">
<div class="nav-info">
<strong>Quick Links</strong>
</div>
<ul>
@foreach($server->nav as $linkObj)
<li><a href="{{ linkObj->link }}">{{ $linkObj->name }}</a></li>
@endforeach
</ul>
</div>
@endforeach
</div>
Each {{ }}
will print out the $server->properties
from the stdClass
object. This is an example of Blade
template and when you call this:
$this->layout->content = View::make('home')->with('servers', $this->getJSON());
The framework looks for the view in app/views/home.blade.php
so make sure you have created the home.blade.php
view file in app/views
folder. This is just a simple idea but you need to read the documentation.