Get Path from node ID I'm using a twig template for a custom block that have images to link to specific nodes. I actually have the node IDs, however generating a relative link doesn't always work. Some pages are using aliases like so
127.0.0.1/web/products and some are using nodes like 127.0.0.1/web/node/19
so using the same relative link doesn't always work. Note that my drupal instance is within a /web/ folder and not at just 127.0.0.1

My twig template looks like this

&lt;div class="row columns"&gt;
    {% for key, image in imageurl %}
    &lt;div class="large-4 medium-3 column"&gt;
        &lt;a href="./node/{{ nid[key] }}"&gt;
            &lt;img src="../sites/default/files/{{ image }}"/&gt;
        &lt;/a&gt;
        &lt;div&gt;
            {{ block_title[key] }}
        &lt;/div&gt;
    &lt;/div&gt;
    {% endfor %}
&lt;/div&gt;


When it appears on 127.0.0.1/web/products the link is

http://127.0.0.1/web/node/15


When it appears on 127.0.0.1/web/node/19 the link is

http://127.0.0.1/web/node/node/9


The image has the same issue, since 'image' only contains the filename.
Is there a way I can automatically generate a link based on a node ID and a file that I know the path to, to account for URLs that may contain aliases?
You should use Drupal 8 classes to generate the link. If you get the nid from an existing node object you can do the following in the .theme-file of your theme:

function yourtheme_preprocess_block(&amp;$vars) {
  $node = Drupal::request()-&gt;attributes-&gt;get('node');
  $vars['link'] = $node-&gt;toUrl()-&gt;setAbsolute();
}


In twig you can output:

&lt;div class="row columns"&gt;
    {% for key, image in imageurl %}
    &lt;div class="large-4 medium-3 column"&gt;
        &lt;a href="{{ link }}"&gt;
            &lt;img src="../sites/default/files/{{ image }}"/&gt;
        &lt;/a&gt;
        &lt;div&gt;
            {{ block_title[key] }}
        &lt;/div&gt;
    &lt;/div&gt;
    {% endfor %}
&lt;/div&gt;


To generate the URL of your node just knowing the nid (here in variable $nid) you can use the following in your .theme-file:

function yourtheme_preprocess_block(&amp;$vars) {
  $options = array('absolute' =&gt; TRUE);
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' =&gt; $nid], $options);
  $vars['link'] = $url-&gt;toString();
}


Again you can use {{ link }} to output the URL where ever you need in yout twig template.