简体   繁体   中英

<%= %> syntax in Typescript/Angular

I'm working on an Angular project that makes use of a variable called WEB_HOST . I can see in another file where the variable is defined (it's somehow defined in a class called ProjectConfig ).

Definition (simplified):

export class ProjectConfig {
  WEB_HOST = 'https://example.com'; // I didn't think properties could be assigned here?

  constructor() { ... }
}

Now, from a completely separate *.ts file, this obviously doesn't work:

let x = WEB_HOST; // x is undefined

However, in the same file, some existing code manages to access the variable's value by using a bizarre string interpolation:

let x = `<%= WEB_HOST %>`; // x == 'https://example.com'

What is going on here? I've never seen this <%= syntax before. Is it part of Angular? Typescript? I haven't been able to find any documentation on what it does.

I also don't know how it manages to get a property out of ProjectConfig (and I'm not sure it's a class property either... the definition being outside of any class function confuses me too).

So, this is ASP Tags.

If you take a look at the following from w3schools. https://www.w3schools.com/asp/showasp.asp?filename=demo_syntax_tags

You will see that it is used in the HTML for templating. It can also be used I believe in other files as it is processed on the server before the client application runs on your browser.

HTH

Looks like ERB, a Ruby templating engine that Ruby on Rails uses. https://codingbee.net/tutorials/ruby/ruby-the-erb-templating-system

Others have mentioned that various languages use <%= some_code_here %> for templating.

Regardless of what language is processing it, I imagine your .ts file runs through some server side framework, that will put some string value in place of WEB_HOST, and then the .ts file will be transpiled to JS.

You could try this way on HTML file

{{window.location.origin}}

if it doesn't recognize the window variable we might need this in ts file

declare const window;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM