Use twig to filter variable into url












0















I have a variable {{ name }} which outputs Treatment & Support. I need to remove the & symbol and convert the name into a useable url slug with twig for example: treatment-support.



I have having trouble finding the correct twig fitlers. I am looking at I am looking at http://twig.sensiolabs.org/documentation. So far all I have is



{{ name |lower }}



To reiterate I need to use twig to turn Treatment & Support into treatment-support using the {{ name }} variable.



Any help is appreciated.










share|improve this question

























  • See github.com/cocur/slugify

    – DarkBee
    May 25 '16 at 6:30






  • 1





    You can also use something like {{ name|replace({' & ': '-'}) }}

    – alexf
    May 25 '16 at 10:10











  • @alex Then what about á à é è ..., there would be too many replaces to put those in a template

    – DarkBee
    May 25 '16 at 12:32






  • 1





    Yes of course, but I didn't know if he will have this use case or if he just has to change '&' :)

    – alexf
    May 25 '16 at 12:34













  • @alexf thank you I also had to replae & {{ name|replace({'& ': '-'}) }} but that worked I had the syntax wrong before. Thank you so much!

    – lookingGlass
    May 25 '16 at 14:29


















0















I have a variable {{ name }} which outputs Treatment & Support. I need to remove the & symbol and convert the name into a useable url slug with twig for example: treatment-support.



I have having trouble finding the correct twig fitlers. I am looking at I am looking at http://twig.sensiolabs.org/documentation. So far all I have is



{{ name |lower }}



To reiterate I need to use twig to turn Treatment & Support into treatment-support using the {{ name }} variable.



Any help is appreciated.










share|improve this question

























  • See github.com/cocur/slugify

    – DarkBee
    May 25 '16 at 6:30






  • 1





    You can also use something like {{ name|replace({' & ': '-'}) }}

    – alexf
    May 25 '16 at 10:10











  • @alex Then what about á à é è ..., there would be too many replaces to put those in a template

    – DarkBee
    May 25 '16 at 12:32






  • 1





    Yes of course, but I didn't know if he will have this use case or if he just has to change '&' :)

    – alexf
    May 25 '16 at 12:34













  • @alexf thank you I also had to replae & {{ name|replace({'& ': '-'}) }} but that worked I had the syntax wrong before. Thank you so much!

    – lookingGlass
    May 25 '16 at 14:29
















0












0








0








I have a variable {{ name }} which outputs Treatment & Support. I need to remove the & symbol and convert the name into a useable url slug with twig for example: treatment-support.



I have having trouble finding the correct twig fitlers. I am looking at I am looking at http://twig.sensiolabs.org/documentation. So far all I have is



{{ name |lower }}



To reiterate I need to use twig to turn Treatment & Support into treatment-support using the {{ name }} variable.



Any help is appreciated.










share|improve this question
















I have a variable {{ name }} which outputs Treatment & Support. I need to remove the & symbol and convert the name into a useable url slug with twig for example: treatment-support.



I have having trouble finding the correct twig fitlers. I am looking at I am looking at http://twig.sensiolabs.org/documentation. So far all I have is



{{ name |lower }}



To reiterate I need to use twig to turn Treatment & Support into treatment-support using the {{ name }} variable.



Any help is appreciated.







filter twig drupal-8






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 25 '16 at 3:34







lookingGlass

















asked May 25 '16 at 3:26









lookingGlasslookingGlass

112213




112213













  • See github.com/cocur/slugify

    – DarkBee
    May 25 '16 at 6:30






  • 1





    You can also use something like {{ name|replace({' & ': '-'}) }}

    – alexf
    May 25 '16 at 10:10











  • @alex Then what about á à é è ..., there would be too many replaces to put those in a template

    – DarkBee
    May 25 '16 at 12:32






  • 1





    Yes of course, but I didn't know if he will have this use case or if he just has to change '&' :)

    – alexf
    May 25 '16 at 12:34













  • @alexf thank you I also had to replae & {{ name|replace({'& ': '-'}) }} but that worked I had the syntax wrong before. Thank you so much!

    – lookingGlass
    May 25 '16 at 14:29





















  • See github.com/cocur/slugify

    – DarkBee
    May 25 '16 at 6:30






  • 1





    You can also use something like {{ name|replace({' & ': '-'}) }}

    – alexf
    May 25 '16 at 10:10











  • @alex Then what about á à é è ..., there would be too many replaces to put those in a template

    – DarkBee
    May 25 '16 at 12:32






  • 1





    Yes of course, but I didn't know if he will have this use case or if he just has to change '&' :)

    – alexf
    May 25 '16 at 12:34













  • @alexf thank you I also had to replae & {{ name|replace({'& ': '-'}) }} but that worked I had the syntax wrong before. Thank you so much!

    – lookingGlass
    May 25 '16 at 14:29



















See github.com/cocur/slugify

– DarkBee
May 25 '16 at 6:30





See github.com/cocur/slugify

– DarkBee
May 25 '16 at 6:30




1




1





You can also use something like {{ name|replace({' & ': '-'}) }}

– alexf
May 25 '16 at 10:10





You can also use something like {{ name|replace({' & ': '-'}) }}

– alexf
May 25 '16 at 10:10













@alex Then what about á à é è ..., there would be too many replaces to put those in a template

– DarkBee
May 25 '16 at 12:32





@alex Then what about á à é è ..., there would be too many replaces to put those in a template

– DarkBee
May 25 '16 at 12:32




1




1





Yes of course, but I didn't know if he will have this use case or if he just has to change '&' :)

– alexf
May 25 '16 at 12:34







Yes of course, but I didn't know if he will have this use case or if he just has to change '&' :)

– alexf
May 25 '16 at 12:34















@alexf thank you I also had to replae & {{ name|replace({'& ': '-'}) }} but that worked I had the syntax wrong before. Thank you so much!

– lookingGlass
May 25 '16 at 14:29







@alexf thank you I also had to replae & {{ name|replace({'& ': '-'}) }} but that worked I had the syntax wrong before. Thank you so much!

– lookingGlass
May 25 '16 at 14:29














3 Answers
3






active

oldest

votes


















3














You can use twig replace filter :



{{ name|replace({' & ': '-', '&': '-'}) }}




As @DarkBee said in comment, for something more complex, you can use Slugify






share|improve this answer































    0














    you can create your own filters in drupal8 for twig.



    follow this:



    http://leopathu.in/content/create-custom-twig-filter-drupal-8



    if didn't work please comment. I have successfully created some filters for my drupal website.






    share|improve this answer































      0














      You could create a custom filter or use the suggestion from @alexf



      however in the event of multiple instances of this, i would suggest using a custom filter



      something like...



      <?php
      $loader = new Twig_Loader_Filesystem();
      $twig = new Twig_Environment($loader);

      /**
      * Creates slugs from strings
      */
      $twig->addFilter(new Twig_Filter('slugify', function( $string = '' ) {

      if( !$string ){
      return $string;
      }

      if( !is_string( $string ) ){
      throw new Exception('Only strings can be slugified.' );
      }

      //lowercase the whole string
      $slug = strtolower($string);

      //create an array of all the words/characters
      $slug_array = explode( ' ', $slug );

      //replace all special characters with empty strings
      array_walk( $slug_array, function( &$item, $key ){
      $item = preg_replace('/[^a-z0-9]/', '', $item );
      return $item;
      });

      //remove empty items from the array
      $slug_array = array_filter( $slug_array );

      //reconstruct the string
      $slug = join( '-', $slug_array );
      return $slug;
      }));


      Then you can use it like so



      <p>{{ 'Treatment & Support'|slugify }}</p>
      <p>{{ 'Heres a sentence with 2 numbers 8o'|slugify }}</p>
      <p>{{ 'Hello World!'|slugify }}</p>


      And that will produce the following output



      treatment-support 
      heres-a-sentence-with-2-numbers-8o
      hello-world





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37427277%2fuse-twig-to-filter-variable-into-url%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        3














        You can use twig replace filter :



        {{ name|replace({' & ': '-', '&amp;': '-'}) }}




        As @DarkBee said in comment, for something more complex, you can use Slugify






        share|improve this answer




























          3














          You can use twig replace filter :



          {{ name|replace({' & ': '-', '&amp;': '-'}) }}




          As @DarkBee said in comment, for something more complex, you can use Slugify






          share|improve this answer


























            3












            3








            3







            You can use twig replace filter :



            {{ name|replace({' & ': '-', '&amp;': '-'}) }}




            As @DarkBee said in comment, for something more complex, you can use Slugify






            share|improve this answer













            You can use twig replace filter :



            {{ name|replace({' & ': '-', '&amp;': '-'}) }}




            As @DarkBee said in comment, for something more complex, you can use Slugify







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 25 '16 at 14:34









            alexfalexf

            1,142720




            1,142720

























                0














                you can create your own filters in drupal8 for twig.



                follow this:



                http://leopathu.in/content/create-custom-twig-filter-drupal-8



                if didn't work please comment. I have successfully created some filters for my drupal website.






                share|improve this answer




























                  0














                  you can create your own filters in drupal8 for twig.



                  follow this:



                  http://leopathu.in/content/create-custom-twig-filter-drupal-8



                  if didn't work please comment. I have successfully created some filters for my drupal website.






                  share|improve this answer


























                    0












                    0








                    0







                    you can create your own filters in drupal8 for twig.



                    follow this:



                    http://leopathu.in/content/create-custom-twig-filter-drupal-8



                    if didn't work please comment. I have successfully created some filters for my drupal website.






                    share|improve this answer













                    you can create your own filters in drupal8 for twig.



                    follow this:



                    http://leopathu.in/content/create-custom-twig-filter-drupal-8



                    if didn't work please comment. I have successfully created some filters for my drupal website.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered May 27 '16 at 12:35









                    Monal SoftMonal Soft

                    105115




                    105115























                        0














                        You could create a custom filter or use the suggestion from @alexf



                        however in the event of multiple instances of this, i would suggest using a custom filter



                        something like...



                        <?php
                        $loader = new Twig_Loader_Filesystem();
                        $twig = new Twig_Environment($loader);

                        /**
                        * Creates slugs from strings
                        */
                        $twig->addFilter(new Twig_Filter('slugify', function( $string = '' ) {

                        if( !$string ){
                        return $string;
                        }

                        if( !is_string( $string ) ){
                        throw new Exception('Only strings can be slugified.' );
                        }

                        //lowercase the whole string
                        $slug = strtolower($string);

                        //create an array of all the words/characters
                        $slug_array = explode( ' ', $slug );

                        //replace all special characters with empty strings
                        array_walk( $slug_array, function( &$item, $key ){
                        $item = preg_replace('/[^a-z0-9]/', '', $item );
                        return $item;
                        });

                        //remove empty items from the array
                        $slug_array = array_filter( $slug_array );

                        //reconstruct the string
                        $slug = join( '-', $slug_array );
                        return $slug;
                        }));


                        Then you can use it like so



                        <p>{{ 'Treatment & Support'|slugify }}</p>
                        <p>{{ 'Heres a sentence with 2 numbers 8o'|slugify }}</p>
                        <p>{{ 'Hello World!'|slugify }}</p>


                        And that will produce the following output



                        treatment-support 
                        heres-a-sentence-with-2-numbers-8o
                        hello-world





                        share|improve this answer




























                          0














                          You could create a custom filter or use the suggestion from @alexf



                          however in the event of multiple instances of this, i would suggest using a custom filter



                          something like...



                          <?php
                          $loader = new Twig_Loader_Filesystem();
                          $twig = new Twig_Environment($loader);

                          /**
                          * Creates slugs from strings
                          */
                          $twig->addFilter(new Twig_Filter('slugify', function( $string = '' ) {

                          if( !$string ){
                          return $string;
                          }

                          if( !is_string( $string ) ){
                          throw new Exception('Only strings can be slugified.' );
                          }

                          //lowercase the whole string
                          $slug = strtolower($string);

                          //create an array of all the words/characters
                          $slug_array = explode( ' ', $slug );

                          //replace all special characters with empty strings
                          array_walk( $slug_array, function( &$item, $key ){
                          $item = preg_replace('/[^a-z0-9]/', '', $item );
                          return $item;
                          });

                          //remove empty items from the array
                          $slug_array = array_filter( $slug_array );

                          //reconstruct the string
                          $slug = join( '-', $slug_array );
                          return $slug;
                          }));


                          Then you can use it like so



                          <p>{{ 'Treatment & Support'|slugify }}</p>
                          <p>{{ 'Heres a sentence with 2 numbers 8o'|slugify }}</p>
                          <p>{{ 'Hello World!'|slugify }}</p>


                          And that will produce the following output



                          treatment-support 
                          heres-a-sentence-with-2-numbers-8o
                          hello-world





                          share|improve this answer


























                            0












                            0








                            0







                            You could create a custom filter or use the suggestion from @alexf



                            however in the event of multiple instances of this, i would suggest using a custom filter



                            something like...



                            <?php
                            $loader = new Twig_Loader_Filesystem();
                            $twig = new Twig_Environment($loader);

                            /**
                            * Creates slugs from strings
                            */
                            $twig->addFilter(new Twig_Filter('slugify', function( $string = '' ) {

                            if( !$string ){
                            return $string;
                            }

                            if( !is_string( $string ) ){
                            throw new Exception('Only strings can be slugified.' );
                            }

                            //lowercase the whole string
                            $slug = strtolower($string);

                            //create an array of all the words/characters
                            $slug_array = explode( ' ', $slug );

                            //replace all special characters with empty strings
                            array_walk( $slug_array, function( &$item, $key ){
                            $item = preg_replace('/[^a-z0-9]/', '', $item );
                            return $item;
                            });

                            //remove empty items from the array
                            $slug_array = array_filter( $slug_array );

                            //reconstruct the string
                            $slug = join( '-', $slug_array );
                            return $slug;
                            }));


                            Then you can use it like so



                            <p>{{ 'Treatment & Support'|slugify }}</p>
                            <p>{{ 'Heres a sentence with 2 numbers 8o'|slugify }}</p>
                            <p>{{ 'Hello World!'|slugify }}</p>


                            And that will produce the following output



                            treatment-support 
                            heres-a-sentence-with-2-numbers-8o
                            hello-world





                            share|improve this answer













                            You could create a custom filter or use the suggestion from @alexf



                            however in the event of multiple instances of this, i would suggest using a custom filter



                            something like...



                            <?php
                            $loader = new Twig_Loader_Filesystem();
                            $twig = new Twig_Environment($loader);

                            /**
                            * Creates slugs from strings
                            */
                            $twig->addFilter(new Twig_Filter('slugify', function( $string = '' ) {

                            if( !$string ){
                            return $string;
                            }

                            if( !is_string( $string ) ){
                            throw new Exception('Only strings can be slugified.' );
                            }

                            //lowercase the whole string
                            $slug = strtolower($string);

                            //create an array of all the words/characters
                            $slug_array = explode( ' ', $slug );

                            //replace all special characters with empty strings
                            array_walk( $slug_array, function( &$item, $key ){
                            $item = preg_replace('/[^a-z0-9]/', '', $item );
                            return $item;
                            });

                            //remove empty items from the array
                            $slug_array = array_filter( $slug_array );

                            //reconstruct the string
                            $slug = join( '-', $slug_array );
                            return $slug;
                            }));


                            Then you can use it like so



                            <p>{{ 'Treatment & Support'|slugify }}</p>
                            <p>{{ 'Heres a sentence with 2 numbers 8o'|slugify }}</p>
                            <p>{{ 'Hello World!'|slugify }}</p>


                            And that will produce the following output



                            treatment-support 
                            heres-a-sentence-with-2-numbers-8o
                            hello-world






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 20 '18 at 9:46









                            Craig WayneCraig Wayne

                            2,10622233




                            2,10622233






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37427277%2fuse-twig-to-filter-variable-into-url%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                How to change which sound is reproduced for terminal bell?

                                Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                                Can I use Tabulator js library in my java Spring + Thymeleaf project?