We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 37693
    • 47 Posts
    The problem
    You have a link TV that the client wants to either enter a resource ID (with no fiddly link [[~ ]] markup), or an external link. They also want the external link to open in a new tab.

    The solution

    Snippet called 'intExtLink'
    <?php
    if (is_numeric ($input)){
    	$url = $modx->makeUrl($input);
    	$fullLink = 'href="'.$url.'"';
    }else{
    	$fullLink = 'href="'.$input.'" target="_blank"';
    }
    return $fullLink;


    Example markup/usage
    [[+tv.link:notempty=`<a [[+tv.link:intExtLink]] title="View more information">`]]
        <img src="[[+tv.image]]">
    [[+tv.link:notempty=`</a>`]]
    

    Hope this helps someone, somewhere.

    Improvements are obviously welcomed.

    Shaun
      • 37693
      • 47 Posts
      Okay, here's an improved version with less markup in the PHP


      Snippet called 'intExtLink'
      <?php
      if (is_numeric ($input)){
      	$input = (int)$input;
      	$result = $modx->makeUrl($input);
      }else{
      	$external = true;
      	$result = $input;
      }
      
      if (($options != '') && ($external == true)){
      	$result = 'target="'.$options.'"';
      } 
      elseif (($options != '') && ($external != true)){
      	return ' ';
      }
      
      return $result;


      Example markup/usage
      [[+tv.link:notempty=`<a href="[[+tv.link:intExtLink]]" [[+tv.link:intExtLink=`_blank`]] title="View more information">`]]
          <img src="[[+tv.image]]">
      [[+tv.link:notempty=`</a>`]]
      


      Notice how you can now name the Target attribute? You could also choose to remove it completely.

      Shaun
        • 40045
        • 534 Posts
        That's nice, but as I don't like to have these target="_blank" attributes in my source code, I like to do this with jQuery like this:

        	$(window).load( function() {
        		$.extend($.expr[':'], {
        			external: function(obj) {
        				return obj.href !== undefined && obj.href !== '' && !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
        			}
        		});
        		// Add target="_blank" to all external links, has to happen at the end of the parsing process!
        		$('a:external, a.newtab').attr('target','_blank');
        	});
        


          • 28042 ☆ A M B ☆
          • 24,524 Posts
          I kind of like the target="new" attribute. Not sure about browser support, but I haven't had any complaints yet.
            Studying MODX in the desert - http://sottwell.com
            Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
            Join the Slack Community - http://modx.org