I have a CMS that I need to modify. I want the external links to open in a new window target="_blank"
Here's the code:
<?php foreach ($this->menus as $menu) { ?>
<a href="<?php echo $menu->type == 'External' ? $menu->link : "/Index/Content/Id/{$menu->id}" ?>">
What I have tried:
<?php echo ($menu->type == 'External') ? "{$menu->link} target=_blank" : "/Index/Content/Id/{$menu->id}" ?>
All links currently open in target blank. How can i make only the external links open in target blank?
You need to close the double quote. Take a look at your rendered HTML & you'll see the problem.
<?php echo ($menu->type == 'External') ?
"{$menu->link} target='_blank'" :
"/Index/Content/Id/{$menu->id}";
. '"' ?>
This has the effect of closing the double quote that you opened with <a href="
and putting the target into quotes. This should solve your problem.
Instead of making manipulation in the src
attribute, make your code more readable:
<?php if( $menu->type == 'External' ) { ?>
<a href="<?php echo $menu->link; ?>" target="_blank">
<?php } else { ?>
<a href="/Index/Content/Id/<?php echo $menu->id; ?>">
<?php } ?>
Currently, this line:
<?php echo ($menu->type == 'External') ? "{$menu->link} target=_blank" : "/Index/Content/Id/{$menu->id}" ?>
Will create a link in this format:
<a href="http://example.com target=_blank">
Changing it to
<?php echo ($menu->type == 'External') ? "{$menu->link}\" target=\"_blank" : "/Index/Content/Id/{$menu->id}" ?>
Will fix it and you could use your way to do it, because you're closing the href
attribute with a double quote (\"
) and only then add the target
attribute when echoing the result of the ternary operator - You need to take into account the you're wrapping with "
the php tag where you echoing the url.